Uncategorized
Fetch MySql Data By PHP API to Flutter App
Admin
January 28, 2024
13 views
First We will create the api for connecting the MySQL table with the flutter app.
<?php
include('cors.php');
include('../database.php');
// Query the database to fetch orders
$query = "SELECT * FROM checkout";
$stmt = $conn->prepare($query);
$stmt->execute();
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($orders) {
// Orders found
$response = [
'success' => true,
'message' => 'Orders fetched successfully',
'orders' => $orders
];
} else {
// No orders found
$response = [
'success' => false,
'message' => 'No orders found',
'orders' => [] // Ensure an empty array is sent if no orders found
];
}
// Send the response as JSON
header('Content-Type: application/json');
echo json_encode($response);
?>
We have created the API and printed the $response for flutter application. Now we will create the flutter screen.
First, we will import the necessary files
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Second, we will create the screen
class MyOrderScreen extends StatefulWidget {
const MyOrderScreen({Key? key}) : super(key: key);
@override
State<MyOrderScreen> createState() => _MyOrderScreenState();
}
class _MyOrderScreenState extends State<MyOrderScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Thank You'),
backgroundColor: Colors.pink,
),
body: SingleChildScrollView(
child: Column(
children: [
SizedBox(height: 50,),
Container(
margin: EdgeInsets.all(10),
alignment: Alignment.center,
child: Text('Your Orders! ', style: TextStyle(fontSize: 25),),
),
],
),
),
);
}
}
Third, we will declare a variable for storing the data of the API
List<Map<String, dynamic>> orders = [];
Fourth, we will create a asynchronous function called fetchorders
Future<void> fetchOrders() async {
final response = await http.get(Uri.parse('https://aboutassam.in/flutter_app/api/orders.php'));
if (response.statusCode == 200) {
final responseData = json.decode(response.body);
if (responseData['success'] == true) {
setState(() {
orders = List<Map<String, dynamic>>.from(responseData['orders']);
});
} else {
throw Exception(responseData['message']);
}
} else {
throw Exception('Failed to load orders');
}
}
Fifth, we will create the listview builder for displaying the data (reference)
ListView.builder(
shrinkWrap: true,
itemCount: orders.length,
itemBuilder: (context, index) {
return ListTile(
title: Text('Order ID: ${orders[index]['id']}'),
subtitle: Text('Name: ${orders[index]['c_name']}'),
trailing: Text('Status: ${orders[index]['status']}'),
);
},
),