call api in flutter example register user data in database
call api in flutter example register user data in database

Hi Guys, Welcome to Proto Coders Point, In this tutorial we will create a registration form with validation and send data to – api call in flutter to store data to database the data in json maped format to php script, and the php script will help in storing data in phpmyadmin database.


So Let’s Begin

#Video Tutorial


My Database  (Phpmyadmin)

phpmyadmin

This is my database, Here in my database i have created a table by name “registered”, This table has 5 field i.e. id, name , email, phone, password. where all our registered use data will get stored.


My PHP API SCRIPT

Connecting to my server database

5 Common Cat Behaviours And What Th...
5 Common Cat Behaviours And What They Mean
connect.php

<?php

//replace username with your phpmyadmin username
//replace password with your phpmyadmin password
// replacce database name with your database name 
$conn = mysqli_connect("localhost", "username", "password", "databasename");

if($conn)
{
  //echo "Connection Success";
}
else
{
  //echo "Connection Failed";

}

?>

The above connect.php code is used to get connected to your phpmyadmin database

Inserting data to our registered table

registration.php

<?php

    $name = $_POST["name"];
    $email= $_POST["email"];
    $phone= $_POST["phone"];
    $password = $_POST["password"];
    
    require_once 'connect.php';

$findexist="select * from registered where name='$name'";

        $resultsearch=mysqli_query($conn,$findexist);
    if(mysqli_num_rows($resultsearch)>0)
    {
           while($row=mysqli_fetch_array($resultsearch))
          {
              $result["success"] = "3";
              $result["message"] = "user Already exist";

              echo json_encode($result);
              mysqli_close($conn);
          }
  }
else{

    $sql = "INSERT INTO registered (name,email,phone,password) VALUES ('$name','$email','$phone','$password');";

    if ( mysqli_query($conn, $sql) ) {
        $result["success"] = "1";
        $result["message"] = "Registration success";

        echo json_encode($result);
        mysqli_close($conn);

    } else {
        $result["success"] = "0";
        $result["message"] = "error in Registration";
        echo json_encode($result);
        mysqli_close($conn);
    }
}

?>

The Above php api script will help use in inserting user data to our database.

In Above code, there are 2 query

First query will help in checking if same user data is present in database, if user data exist then php code will send response saying ” user exist ”

Second query will insert data in our database table.


So Now our server script is ready to get data from our flutter app, Now let’s Build flutter app that will send data to php script.

Snippet code that sends  data to server using Flutter http library – api call in flutter

Future RegistrationUser()  async{
    // url to registration php script
    var APIURL = "https://protocoderspoint.com/php/registration.php";

    //json maping user entered details
    Map mapeddate ={
      'name':_name.text,
      'email':_email.text,
      'phone':_phone.text,
      'password':_password.text
    };
    //send  data using http post to our php code
    http.Response reponse = await http.post(APIURL,body:mapeddate );
    
    //getting response from php code, here
    var data = jsonDecode(reponse.body);
    print("DATA: ${data}");

  }

Complete Flutter Code to send registration form data to API Script (PHP Script)

import 'dart:convert';

import 'package:flutter/material.dart';
import 'InputDeco_design.dart';
import 'package:http/http.dart' as http;


class FormPage extends StatefulWidget {
  @override
  _FormPageState createState() => _FormPageState();
}

class _FormPageState extends State<FormPage> {

  TextEditingController _name = TextEditingController();
  TextEditingController _email = TextEditingController();
  TextEditingController _phone = TextEditingController();
  TextEditingController _password = TextEditingController();
  TextEditingController _confirmpassword = TextEditingController();

  final GlobalKey<FormState> _formkey = GlobalKey<FormState>();


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SingleChildScrollView(
          child: Form(
             key: _formkey,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CircleAvatar(
                  radius: 70,
                  child: Image.network("https://protocoderspoint.com/wp-content/uploads/2020/10/PROTO-CODERS-POINT-LOGO-water-mark-.png"),
                ),
                SizedBox(
                  height: 15,
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom:15,left: 10,right: 10),
                  child: TextFormField(
                    controller: _name,
                    keyboardType: TextInputType.text,
                    decoration: buildInputDecoration(Icons.person,"Full Name"),
                    validator: (String value){
                      if(value.isEmpty)
                        {
                          return "Please enter name";
                        }
                      return null;
                    },
                    onSaved: (String name){

                    },

                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom: 15,left: 10,right: 10),
                  child: TextFormField(
                    controller: _email,
                    keyboardType: TextInputType.text,
                    decoration:buildInputDecoration(Icons.email,"Email"),
                    validator: (String value){
                      if(value.isEmpty)
                      {
                        return "Please enter  email";
                      }
                      if(!RegExp("^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+.[a-z]").hasMatch(value))
                      {
                        return "Please enter valid email";
                      }
                      return null;
                    },
                    onSaved: (String email){

                    },

                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom: 15,left: 10,right: 10),
                  child: TextFormField(
                    controller: _phone,
                    keyboardType: TextInputType.number,
                    decoration:buildInputDecoration(Icons.phone,"Phone No"),
                    validator: (String value){
                      if(value.isEmpty)
                      {
                        return "Please enter  phone";
                      }
                      if(value.length < 9)
                      {
                        return "Please enter valid phone";
                      }
                      return null;
                    },
                    onSaved: (String phone){

                    },
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom: 15,left: 10,right: 10),
                  child: TextFormField(
                    controller: _password,
                    keyboardType: TextInputType.text,
                    decoration:buildInputDecoration(Icons.lock,"Password"),
                    validator: (String value){
                      if(value.isEmpty)
                      {
                        return "Please enter password";
                      }

                      return null;
                    },

                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom: 15,left: 10,right: 10),
                  child: TextFormField(
                    controller: _confirmpassword,
                    obscureText: true,
                    keyboardType: TextInputType.text,
                    decoration:buildInputDecoration(Icons.lock,"Confirm Password"),
                    validator: (String value){
                      if(value.isEmpty)
                      {
                        return "Please enter re-password";
                      }
                      if(_password.text != _confirmpassword.text)
                      {
                        return "Password Do not match";
                      }
                      return null;
                    },


                  ),
                ),

                SizedBox(
                  width: 200,
                  height: 50,
                  child: RaisedButton(
                    color: Colors.redAccent,
                    onPressed: (){

                      if(_formkey.currentState.validate())
                        {
                           RegistrationUser();
                          print("Successful");
                        }else
                          {

                             print("Unsuccessfull");
                          }
                      
                    },
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(50.0),
                        side: BorderSide(color: Colors.blue,width: 2)
                    ),
                    textColor:Colors.white,child: Text("Submit"),

                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  Future RegistrationUser()  async{
    // url to registration php script
    var APIURL = "https://protocoderspoint.com/php/registration.php";

    //json maping user entered details
    Map mapeddate ={
      'name':_name.text,
      'email':_email.text,
      'phone':_phone.text,
      'password':_password.text
    };
    //send  data using http post to our php code
    http.Response reponse = await http.post(APIURL,body:mapeddate );

    //getting response from php code, here
    var data = jsonDecode(reponse.body);
    print("DATA: ${data}");

  }
}