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