Flutter Insert Record to MySQL using PHP API's | Flutter Tutorials in Urdu | Hindi

4 min read 1 year ago
Published on Aug 09, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial will guide you through the process of inserting a record into a MySQL database using PHP APIs in a Flutter application. You'll learn how to design a Flutter UI, create a MySQL database, set up a PHP API, and test your app. This tutorial is particularly useful for beginners looking to integrate Flutter with backend services.

Step 1: Design the Flutter UI

Start by creating a simple user interface that allows users to input data to be sent to the MySQL database.

  • Create a new Flutter project using your preferred IDE.
  • Build the UI using Flutter widgets. The UI should include:
    • Text fields for user input (e.g., name, email).
    • A button to trigger the insert operation.

Example code for the UI:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Insert Record')),
        body: InsertRecordForm(),
      ),
    );
  }
}

class InsertRecordForm extends StatefulWidget {
  @override
  _InsertRecordFormState createState() => _InsertRecordFormState();
}

class _InsertRecordFormState extends State<InsertRecordForm> {
  final TextEditingController nameController = TextEditingController();
  final TextEditingController emailController = TextEditingController();

  void insertRecord() {
    // Logic to insert record will go here
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        TextField(controller: nameController, decoration: InputDecoration(labelText: 'Name')),
        TextField(controller: emailController, decoration: InputDecoration(labelText: 'Email')),
        ElevatedButton(onPressed: insertRecord, child: Text('Insert Record')),
      ],
    );
  }
}

Step 2: Create the MySQL Database

Next, you need to set up a MySQL database to store the records.

  • Access your MySQL server (e.g., using phpMyAdmin).
  • Create a new database named flutter_db.
  • Create a new table called users with the following fields:
    • id (INT, AUTO_INCREMENT, PRIMARY KEY)
    • name (VARCHAR)
    • email (VARCHAR)

SQL query to create the table:

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100)
);

Step 3: Set Up the PHP API

Now, you will create a PHP script that will handle incoming requests and insert data into your MySQL database.

  • Create a new PHP file, for instance, insert.php.
  • Use the following code to connect to the database and insert data:
<?php
$servername = "localhost"; // Change if necessary
$username = "your_username"; // Database username
$password = "your_password"; // Database password
$dbname = "flutter_db"; // Database name

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = $_POST['name'];
    $email = $_POST['email'];
    
    $sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
    
    if ($conn->query($sql) === TRUE) {
        echo "Record inserted successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

$conn->close();
?>

Step 4: Call the API from Flutter

In this step, you will implement the logic to send data from your Flutter app to the PHP API.

  • Import the necessary packages in your Flutter project:
import 'package:http/http.dart' as http;
import 'dart:convert';
  • Update the insertRecord function to make the API call:
void insertRecord() async {
  final response = await http.post(
    Uri.parse('http://your_server_address/insert.php'),
    body: {
      'name': nameController.text,
      'email': emailController.text,
    },
  );

  if (response.statusCode == 200) {
    // Handle successful response
    print('Record inserted: ${response.body}');
  } else {
    // Handle error
    print('Failed to insert record');
  }
}

Step 5: Test the Application

Finally, you will test your application to ensure that the data is being inserted correctly.

  • Run your Flutter app on an emulator or a physical device.
  • Enter data into the fields and click the insert button.
  • Check your MySQL database to verify that the record has been inserted.

Conclusion

In this tutorial, you learned how to insert records into a MySQL database using PHP APIs in a Flutter application. By following these steps, you should now have a functional app that can connect to a database and handle data insertion. For further exploration, consider implementing features like data retrieval and deletion, or enhancing the UI for better user experience.