Posted in API Dart Flutter

Flutter – How to write data in MySQL Database with PHP REST API

Flutter – How to write data in MySQL Database with PHP REST API Posted on June 2, 2020Leave a comment
I'm Hari Prasad Chaudhary from Nepal, developer of the finest educational website/app "MeroSpark" and the finest eCommerce system "PasalaY". Here I share the code snippet which I learn during development.

When you are making a web-based app for mobiles, databases are on the servers, so you have to communicate with the server using REST API. In this example, you can learn how to write data from the flutter app to MySQL database with PHP using the REST API. See the example below, read the explanations comments in the code for better understanding.

flutter form php mysql database

See this also: Flutter – Serialize Nested/Complex JSON From Network and Build List with Refresh Indicator

Our Database Table Structure at phpMyAdmin:

Note: student_id column is with “AUTO_INCREMENT” constraints, so that, the value get automatically increased on INSERT.

PHP Code at server: test/write.php

<?php 
  $db = "test_db"; //database name
  $dbuser = "root"; //database username
  $dbpassword = "root"; //database password
  $dbhost = "localhost"; //database host

  $return["error"] = false;
  $return["message"] = "";

  $link = mysqli_connect($dbhost, $dbuser, $dbpassword, $db);
  //connecting to database server

  $val = isset($_POST["name"]) && isset($_POST["address"])
         && isset($_POST["class"]) && isset($_POST["rollno"]);

  if($val){
       //checking if there is POST data

       $name = $_POST["name"]; //grabing the data from headers
       $address = $_POST["address"];
       $class = $_POST["class"];
       $rollno = $_POST["rollno"];

       //validation name if there is no error before
       if($return["error"] == false && strlen($name) < 3){
           $return["error"] = true;
           $return["message"] = "Enter name up to 3 characters.";
       }

       //add more validations here

       //if there is no any error then ready for database write
       if($return["error"] == false){
            $name = mysqli_real_escape_string($link, $name);
            $address = mysqli_real_escape_string($link, $address);
            $class = mysqli_real_escape_string($link, $class);
            $rollno = mysqli_real_escape_string($link, $rollno);
            //escape inverted comma query conflict from string

            $sql = "INSERT INTO student_list SET
                                full_name = '$name',
                                address = '$address',
                                class = '$class',
                                roll_no = '$rollno'";
            //student_id is with AUTO_INCREMENT, so its value will increase automatically

            $res = mysqli_query($link, $sql);
            if($res){
                //write success
            }else{
                $return["error"] = true;
                $return["message"] = "Database error";
            }
       }
  }else{
      $return["error"] = true;
      $return["message"] = 'Send all parameters.';
  }

  mysqli_close($link); //close mysqli

  header('Content-Type: application/json');
  // tell browser that its a json data
  echo json_encode($return);
  //converting array to JSON string
?>

At Flutter part, add http flutter package in your dependency by adding the following line in pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  http: ^0.12.1

See this also: Flutter – How to make Login Form and validate with PHP MySQL

Complete Flutter Dart Code:

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:http/http.dart' as http;
//import package file manually

void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return  MaterialApp(
         theme: ThemeData(
            primarySwatch:Colors.red, //primary color for theme
         ),
         home: WriteSQLdata() //set the class here
    );
  }
}

class WriteSQLdata extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
     return WriteSQLdataState();
  }
}

class WriteSQLdataState extends State<WriteSQLdata>{

  TextEditingController namectl = TextEditingController();
  TextEditingController addressctl = TextEditingController();
  TextEditingController classctl = TextEditingController();
  TextEditingController rollnoctl = TextEditingController();
  //text controller for TextField

  bool error, sending, success;
  String msg;

  String phpurl = "http://192.168.0.101/test/write.php";
  // do not use http://localhost/ for your local
  // machine, Android emulation do not recognize localhost
  // insted use your local ip address or your live URL
  // hit "ipconfig" on Windows or  "ip a" on Linux to get IP Address

  @override
  void initState() {
      error = false;
      sending = false;
      success = false;
      msg = "";
      super.initState();
  }

  Future<void> sendData() async {

     var res = await http.post(phpurl, body: { 
          "name": namectl.text,
          "address": addressctl.text,
          "class": classctl.text,
          "rollno": rollnoctl.text,
      }); //sending post request with header data

     if (res.statusCode == 200) {
       print(res.body); //print raw response on console
       var data = json.decode(res.body); //decoding json to array
       if(data["error"]){
          setState(() { //refresh the UI when error is recieved from server
             sending = false;
             error = true;
             msg = data["message"]; //error message from server
          });
       }else{
         
         namectl.text = "";
         addressctl.text = "";
         classctl.text = "";
         rollnoctl.text = "";
         //after write success, make fields empty

          setState(() {
             sending = false;
             success = true; //mark success and refresh UI with setState
          });
       }
       
    }else{
       //there is error
        setState(() {
            error = true;
            msg = "Error during sendign data.";
            sending = false;
            //mark error and refresh UI with setState
        });
    }
  }

  @override
  Widget build(BuildContext context) {
     return Scaffold(
        appBar: AppBar(
           title:Text("Write Data PHP & MySQL"),
           backgroundColor:Colors.redAccent
        ), //appbar

        body: SingleChildScrollView( //enable scrolling, when keyboard appears,
                                   // hight becomes small, so prevent overflow
           child:Container( 
              padding: EdgeInsets.all(20),
              child: Column(children: <Widget>[
                
                Container( 
                  child:Text(error?msg:"Enter Student Information"), 
                  //if there is error then sho msg, other wise show text message
                ),

                Container( 
                   child:Text(success?"Write Success":"send data"),
                   //is there is success then show "Write Success" else show "send data"
                ),

                Container( 
                  child: TextField( 
                     controller: namectl,
                     decoration: InputDecoration(
                        labelText:"Full Name:",
                        hintText:"Enter student full name",
                     ),
                  )
                ), //text input for name

                Container( 
                  child: TextField( 
                     controller: addressctl,
                     decoration: InputDecoration(
                        labelText:"Address:",
                        hintText:"Enter student address",
                     ),
                  )
                ), //text input for address

                Container( 
                  child: TextField(
                     controller: classctl,
                     decoration: InputDecoration(
                        labelText:"Class:",
                        hintText:"Enter student class",
                     ),
                  )
                ), //text input for class

                Container( 
                  child: TextField( 
                     controller: rollnoctl,
                     decoration: InputDecoration(
                        labelText:"Roll No:",
                        hintText:"Enter student rollno",
                     ),
                  )
                ), //text input for roll no

                Container( 
                   margin: EdgeInsets.only(top:20),
                   child:SizedBox( 
                     width: double.infinity,
                     child:RaisedButton(
                        onPressed:(){ //if button is pressed, setstate sending = true, so that we can show "sending..."
                          setState(() {
                             sending = true;
                          });
                          sendData();
                        },
                        child: Text(
                          sending?"Sending...":"SEND DATA",
                          //if sending == true then show "Sending" else show "SEND DATA";
                        ), 
                        color: Colors.redAccent,
                        colorBrightness: Brightness.dark,
                        //background of button is darker color, so set brightness to dark
                     )
                   )
                )
              ],)
           )
        ),
     );
  }
}

In this, way you can make Form in flutter and send data to PHP server and write in MySQL database using REST API.

I'm Hari Prasad Chaudhary from Nepal, developer of the finest educational website/app "MeroSpark" and the finest eCommerce system "PasalaY". Here I share the code snippet which I learn during development.

Leave a Reply

Your email address will not be published. Required fields are marked *