Sending Data From Flutter To MySql Database Using PHP
By Webotapp Academy•
<!-- wp:paragraph -->\n<p>In this article we will do three major tasks:</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:list {\"ordered\":true} -->\n<ol><!-- wp:list-item -->\n<li>Create Sql Table </li>\n<!-- /wp:list-item -->\n\n<!-- wp:list-item -->\n<li>Create the flutter <strong>checkout</strong> screen</li>\n<!-- /wp:list-item -->\n\n<!-- wp:list-item -->\n<li>Create API using PHP</li>\n<!-- /wp:list-item --></ol>\n<!-- /wp:list -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">Step 1: Create SQL Table</h3>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>CREATE TABLE checkout (\n id INT PRIMARY KEY,\n c_name VARCHAR(255),\n c_mobile VARCHAR(10),\n c_state VARCHAR(255),\n c_address TEXT\n);</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:paragraph -->\n<p>The above SQL code creates a table called \"<strong>checkout</strong>\" with columns for storing customer information, including a unique identifier (<code>id</code>), name (<code>c_name</code>), mobile number (<code>c_mobile</code>), state (<code>c_state</code>), and address (<code>c_address</code>). The table is designed to efficiently store and retrieve customer checkout data for use in an application.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">Step 2: Create a Flutter Screen Called Checkout</h3>\n<!-- /wp:heading -->\n\n<!-- wp:paragraph -->\n<p>Certainly! Let's break down the Flutter code for the Checkout Screen and explain it step by step for your blog post. This code handles form input and sends data to a server using HTTP POST requests.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p><strong>Flutter Screen Part 1: Import Dependencies</strong></p>\n<!-- /wp:paragraph -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>import 'package:ecommerce_app/Home/Home.dart';\nimport 'package:flutter/material.dart';\nimport 'package:http/http.dart' as http;</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:paragraph -->\n<p>In this step, you import the necessary packages, including the Flutter framework, a custom Home widget, and the <code>http</code> package for making HTTP requests.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p><strong><strong>Flutter Screen Part</strong> 2: Create a Stateful Widget for CheckoutScreen</strong></p>\n<!-- /wp:paragraph -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>class CheckoutScreen extends StatefulWidget {\n const CheckoutScreen({Key? key}) : super(key: key);\n\n @override\n _CheckoutScreenState createState() => _CheckoutScreenState();\n}</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:paragraph -->\n<p>This step defines a stateful widget for the Checkout Screen. It extends <code>StatefulWidget</code> and specifies that it will use <code>_CheckoutScreenState</code> for its state.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p><strong><strong>Flutter Screen Part</strong> 3: Define State and Initialize Variables</strong></p>\n<!-- /wp:paragraph -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>class _CheckoutScreenState extends State<CheckoutScreen> {\n final _formKey = GlobalKey<FormState>();\n String selectedState = 'Select State';\n // Other variable declarations...\n}</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:paragraph -->\n<p>In this part, you create the state for the <code>CheckoutScreen</code>. You initialize a form key, a variable for the selected state, and other variables as needed for your form fields.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p><strong><strong>Flutter Screen Part</strong> 4: Build the Scaffold and UI</strong></p>\n<!-- /wp:paragraph -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>@override\nWidget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n title: Text('Checkout Now'),\n backgroundColor: Colors.pink,\n ),\n body: SingleChildScrollView(\n child: Column(\n children: [\n // UI components such as images, headings, and the form...\n ],\n ),\n ),\n );\n}</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:paragraph -->\n<p>This step defines the UI of the Checkout Screen within a <code>Scaffold</code>. It includes an app bar, an image, a form, and other UI components.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p><strong><strong>Flutter Screen Part</strong> 5: Create Form Fields</strong></p>\n<!-- /wp:paragraph -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>Widget _buildTextInputField(\n String labelText, TextEditingController controller, {\n TextInputType inputType = TextInputType.text,\n String? Function(String?)? validator,\n}) {\n return TextFormField(\n controller: controller,\n decoration: InputDecoration(\n labelText: labelText,\n border: OutlineInputBorder(\n borderRadius: BorderRadius.circular(50),\n borderSide: BorderSide(color: Colors.pink),\n ),\n ),\n keyboardType: inputType,\n validator: validator,\n );\n}</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:paragraph -->\n<p>This part defines a function <code>_buildTextInputField</code> to create text input fields for the form. It allows customization of input type and validation.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p><strong><strong>Flutter Screen Part</strong> 6: Create the State Dropdown</strong></p>\n<!-- /wp:paragraph -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>Widget _buildStateDropdown() {\n return DropdownButtonFormField<String>(\n // Dropdown UI...\n );\n}</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:paragraph -->\n<p>This function creates a state dropdown field. It uses <code>DropdownButtonFormField</code> and builds a dropdown list of Indian states.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p><strong><strong>Flutter Screen Part</strong> 7: Handle Form Submission</strong></p>\n<!-- /wp:paragraph -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>void sendDataToServer() async {\n // Create a map of the form data...\n // Make an HTTP POST request to send the form data...\n}</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:paragraph -->\n<p>This function, <code>sendDataToServer</code>, is called when the user submits the form. It creates a map of form data and sends it to the server via an HTTP POST request using the <code>http</code> package. The response is handled based on its status code.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p><strong><strong>Flutter Screen Part</strong> 8: Handle Response and Navigation</strong></p>\n<!-- /wp:paragraph -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>if (response.statusCode == 200) {\n // Request was successful, you can handle the response here...\n} else {\n // Request failed, handle the error...\n}</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:paragraph -->\n<p>In this part, you check the response status code. If the request is successful (status code 200), you can handle the response. If there's an error, you handle it accordingly. In this example, if the request is successful, it navigates to the \"Home\" screen using <code>Navigator</code>.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p></p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p><strong><strong>Flutter Screen </strong>Final: Full Source Code</strong></p>\n<!-- /wp:paragraph -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>import 'package:ecommerce_app/Home/Home.dart';\nimport 'package:flutter/material.dart';\nimport 'package:http/http.dart' as http; // Import the http package.\n\nclass CheckoutScreen extends StatefulWidget {\n const CheckoutScreen({Key? key}) : super(key: key);\n\n @override\n _CheckoutScreenState createState() => _CheckoutScreenState();\n}\n\nclass _CheckoutScreenState extends State<CheckoutScreen> {\n final _formKey = GlobalKey<FormState>();\n String selectedState = 'Select State';\n\n List<String> indianStates = [\n 'Select State',\n 'Andhra Pradesh',\n 'Arunachal Pradesh',\n 'Assam',\n 'Bihar',\n 'Chhattisgarh',\n 'Goa',\n 'Gujarat',\n 'Haryana',\n 'Himachal Pradesh',\n 'Jharkhand',\n 'Karnataka',\n 'Kerala',\n 'Madhya Pradesh',\n 'Maharashtra',\n 'Manipur',\n 'Meghalaya',\n 'Mizoram',\n 'Nagaland',\n 'Odisha',\n 'Punjab',\n 'Rajasthan',\n 'Sikkim',\n 'Tamil Nadu',\n 'Telangana',\n 'Tripura',\n 'Uttar Pradesh',\n 'Uttarakhand',\n 'West Bengal',\n // Rest of the states\n ];\n\n // Define controllers for the form fields to get their values.\n TextEditingController nameController = TextEditingController();\n TextEditingController mobileController = TextEditingController();\n TextEditingController addressController = TextEditingController();\n\n @override\n void dispose() {\n nameController.dispose();\n mobileController.dispose();\n addressController.dispose();\n super.dispose();\n }\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n title: Text('Checkout Now'),\n backgroundColor: Colors.pink,\n ),\n body: SingleChildScrollView(\n child: Column(\n children: [\n Container(\n margin: EdgeInsets.all(30),\n child: Image.network('https://booppers.tk/assets/img/cart.png'),\n ),\n SizedBox(height: 20),\n Container(\n margin: EdgeInsets.all(10),\n alignment: Alignment.center,\n child: Text('Checkout Now', style: TextStyle(fontSize: 25)),\n ),\n Form(\n key: _formKey,\n child: Column(\n children: <Widget>[\n _buildTextInputField('Your Name', nameController),\n SizedBox(height: 20),\n _buildTextInputField('Your Mobile Number', mobileController,\n inputType: TextInputType.number,\n validator: (value) {\n if (value!.isEmpty) {\n return 'Please enter your mobile number';\n } else if (value.length != 10) {\n return 'Mobile number should be 10 digits';\n }\n return null;\n }),\n SizedBox(height: 20),\n _buildStateDropdown(),\n SizedBox(height: 20),\n _buildTextInputField('Your Address', addressController),\n ElevatedButton(\n onPressed: () {\n if (_formKey.currentState!.validate()) {\n // Form is valid, send data to the server.\n sendDataToServer();\n }\n },\n child: Text('Submit'),\n ),\n ],\n ),\n ),\n ],\n ),\n ),\n );\n }\n\n Widget _buildTextInputField(\n String labelText, TextEditingController controller, {\n TextInputType inputType = TextInputType.text,\n String? Function(String?)? validator,\n }) {\n return TextFormField(\n controller: controller,\n decoration: InputDecoration(\n labelText: labelText,\n border: OutlineInputBorder(\n borderRadius: BorderRadius.circular(50),\n borderSide: BorderSide(color: Colors.pink),\n ),\n ),\n keyboardType: inputType,\n validator: validator,\n );\n }\n\n Widget _buildStateDropdown() {\n return DropdownButtonFormField<String>(\n decoration: InputDecoration(\n labelText: 'Your State',\n border: OutlineInputBorder(\n borderRadius: BorderRadius.circular(50),\n borderSide: BorderSide(color: Colors.pink),\n ),\n ),\n value: selectedState,\n items: indianStates.map((state) {\n return DropdownMenuItem<String>(\n value: state,\n child: Text(state),\n );\n }).toList(),\n onChanged: (value) {\n setState(() {\n selectedState = value!;\n });\n },\n );\n }\n\n void sendDataToServer() async {\n // Create a map of the form data.\n Map<String, String> formData = {\n 'name': nameController.text,\n 'mobile': mobileController.text,\n 'state': selectedState,\n 'address': addressController.text,\n };\n\n // Make an HTTP POST request to send the form data.\n final response = await http.post(\n Uri.parse('https://booppers.tk/api/checkout.php'),\n body: formData,\n );\n\n if (response.statusCode == 200) {\n // Request was successful, you can handle the response here.\n print('Response: ${response.body}');\n // Request was successful, navigate to the thank you page.\n Navigator.push(\n context,\n MaterialPageRoute(builder: (context) => Home()),\n );\n } else {\n // Request failed, handle the error.\n print('Error: ${response.reasonPhrase}');\n }\n }\n}\n</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">Step 3: Create API Using PHP</h3>\n<!-- /wp:heading -->\n\n<!-- wp:paragraph -->\n<p>Here's the PHP code for handling a POST request and inserting data into a MySQL database:</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p><strong>PHP API Part 1: Import Necessary Files and Establish a Database Connection</strong></p>\n<!-- /wp:paragraph -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code><?php\n// Include necessary files and establish a PDO database connection.\ninclude('cors.php'); // Include CORS handling if needed.\ninclude('../database.php'); // Include the database connection script.</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:paragraph -->\n<p>In this step, you import any required files and establish a connection to your MySQL database using PDO. Replace <code>'cors.php'</code> and <code>'../database.php'</code> with the actual file paths or include statements for your project. The <code>database.php</code> file should contain the database connection details.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p><strong><strong>PHP API Part</strong></strong> <strong>2: Set Response Content Type to JSON</strong></p>\n<!-- /wp:paragraph -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>// Set the response content type to JSON.\nheader('Content-Type: application/json');</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:paragraph -->\n<p>This sets the HTTP response header to indicate that the response will be in JSON format.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p><strong><strong>PHP API Part</strong> 3: Initialize an Empty Response Array</strong></p>\n<!-- /wp:paragraph -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>// Initialize an empty response array to hold the result.\n$response = array();</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:paragraph -->\n<p>You create an empty associative array named <code>$response</code> to store the response data that will be sent back to the client.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p><strong><strong>PHP API Part</strong> 4: Check Request Method</strong></p>\n<!-- /wp:paragraph -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>// Check if the request is a POST request.\nif ($_SERVER['REQUEST_METHOD'] === 'POST') {\n // Handle the POST request here.\n} else {\n // Handle other request methods (e.g., GET).\n}</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:paragraph -->\n<p>This part checks the HTTP request method. It specifically looks for POST requests. If the request method is POST, the code inside the <code>if</code> block will be executed.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p><strong><strong>PHP API Part</strong> 5: Retrieve Data from the POST Request</strong></p>\n<!-- /wp:paragraph -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>// Get data from the POST request.\n$c_name = $_POST['name'];\n$c_mobile = $_POST['mobile'];\n$c_state = $_POST['state'];\n$c_address = $_POST['address'];</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:paragraph -->\n<p>Here, you retrieve data from the POST request. It assumes that the POST data includes fields named 'name,' 'mobile,' 'state,' and 'address.' These values will be used to insert data into the database.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p>This is where you retrieve the values sent by the Flutter application when a user submits the form.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p><strong><strong>PHP API Part</strong> 6: Create SQL Query and Prepared Statement</strong></p>\n<!-- /wp:paragraph -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>// Create an SQL query to insert the data into the database using prepared statements.\n$sql = \"INSERT INTO checkout (c_name, c_mobile, c_state, c_address) VALUES (:name, :mobile, :state, :address)\";\n\n// Prepare the SQL statement for execution.\n$stmt = $conn->prepare($sql);</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:paragraph -->\n<p>In this step, you define the SQL query that will insert data into your database table, \"checkout.\" You use prepared statements for security. The <code>:name</code>, <code>:mobile</code>, <code>:state</code>, and <code>:address</code> are placeholders for values that will be inserted later.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p><strong><strong>PHP API Part</strong> 7: Bind Parameters to Prepared Statement</strong></p>\n<!-- /wp:paragraph -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>// Bind the parameters to the prepared statement.\n$stmt->bindParam(':name', $c_name);\n$stmt->bindParam(':mobile', $c_mobile);\n$stmt->bindParam(':state', $c_state);\n$stmt->bindParam(':address', $c_address);</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:paragraph -->\n<p>Here, you bind the values you retrieved from the POST request to the placeholders in the prepared statement. This process ensures that data is securely inserted into the database.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p><strong><strong>PHP API Part</strong> 8: Execute the Prepared Statement and Handle Success/Failure</strong></p>\n<!-- /wp:paragraph -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>// Execute the prepared statement.\nif ($stmt->execute()) {\n // If data insertion is successful, set success to true and provide a success message.\n $response['success'] = true;\n $response['message'] = \"Data inserted successfully.\";\n} else {\n // If an error occurs during data insertion, set success to false and provide an error message.\n $response['success'] = false;\n $response['message'] = \"Error: \" . $stmt->errorInfo();\n}</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:paragraph -->\n<p>In this step, you execute the prepared statement. If the insertion is successful, you set the <code>success</code> key in the response array to <code>true</code> and provide a success message. If an error occurs during data insertion, <code>success</code> is set to <code>false</code>, and you provide an error message. The <code>errorInfo()</code> method is used to fetch the error details.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p><strong><strong>PHP API Part</strong> 9: Handle Invalid Request Method</strong></p>\n<!-- /wp:paragraph -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>} else {\n // If the request method is not POST, set success to false and provide an error message for an invalid request method.\n $response['success'] = false;\n $response['message'] = \"Invalid request method.\";\n}</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:paragraph -->\n<p>This part of the code handles cases where the HTTP request method is not POST. In such cases, the <code>success</code> key is set to <code>false</code>, and an error message is provided, indicating that the request method is invalid.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p><strong><strong>PHP API Part</strong> 10: Output the Response as JSON</strong></p>\n<!-- /wp:paragraph -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>// Output the response as a JSON-encoded string.\necho json_encode($response);</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:paragraph -->\n<p>Finally, you convert the response array into a JSON-encoded string and send it as the HTTP response to the Flutter client.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p>This code serves as the backend API for your Flutter application, allowing it to send checkout data to the server for storage in the MySQL database. It also handles errors and sends informative responses back to the client.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:paragraph -->\n<p><strong>PHP API Full Source Code</strong></p>\n<!-- /wp:paragraph -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code><?php\ninclude('cors.php');\ninclude('../database.php');\n\n// Assuming you have already established a PDO database connection in database.php\n// Replace database credentials with your own.\n\nheader('Content-Type: application/json');\n\n// Initialize an empty response.\n$response = array();\n\n// Check if the request is a POST request.\nif ($_SERVER['REQUEST_METHOD'] === 'POST') {\n // Get data from the POST request.\n $c_name = $_POST['name'];\n $c_mobile = $_POST['mobile'];\n $c_state = $_POST['state'];\n $c_address = $_POST['address'];\n\n // Insert the data into the database using prepared statements.\n $sql = \"INSERT INTO checkout (c_name, c_mobile, c_state, c_address) VALUES (:name, :mobile, :state, :address)\";\n $stmt = $conn->prepare($sql);\n \n // Bind the parameters.\n $stmt->bindParam(':name', $c_name);\n $stmt->bindParam(':mobile', $c_mobile);\n $stmt->bindParam(':state', $c_state);\n $stmt->bindParam(':address', $c_address);\n\n if ($stmt->execute()) {\n $response['success'] = true;\n $response['message'] = \"Data inserted successfully.\";\n } else {\n $response['success'] = false;\n $response['message'] = \"Error: \" . $stmt->errorInfo();\n }\n} else {\n $response['success'] = false;\n $response['message'] = \"Invalid request method.\";\n}\n\n// Output the response as JSON.\necho json_encode($response);\n?>\n</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:paragraph -->\n<p></p>\n<!-- /wp:paragraph -->