Search code examples
mysqlhttpfluttercrudsocketexception

Flutter: Connection to mysql server is not working


I am trying to connect flutter with mysql database for sql crud operations but it is not working. This is the error I'm getting SocketException: OS Error: Connection refused, errno = 111, address = 127.0.0.1, port = 45896

This is my code for API request

import 'package:http/http.dart' as http;
import 'dart:async';

class Services{
  static const ROOT = 'http://127.0.0.1/practice/service.php';
  static const _CREATE_TABLE_ACTION = 'CREATE_TABLE';
  static const _ADD_EMP_ACTION = 'ADD_EMP';


//method to create table employees
static Future<String> createTable() async{
  try{
    //add parameters to pass to the request
    var map = Map<String, dynamic>();
    map['action'] = _CREATE_TABLE_ACTION;
    final response = await http.post(ROOT,body:map);
    print(response.body);
    //print('CREATE TABLE RESPONSE: ${response.body}');
    return response.body;
  }
  catch (e){
      print(e);
    return "error";
  }
}


//method to add an employee to database
static Future<String> addEmployee(String firstName, String lastName) async{
  try{
    //add parameters to pass to the request
    var map = Map<String, dynamic>();
    map['action'] = _ADD_EMP_ACTION;
    map['first_name'] = firstName;
    map['last_name'] = lastName;
    final response = await http.post(ROOT,body:map);
    print('Insert response: ${response.body}');
    if(200 == response.statusCode){
      return response.body;
    }
    else{
      return "error";
    }
  }
  catch (e){
    print(e);
    return "error";
  }
}
}

This is the function calling the code for creating the table

  _createTable(){
    _showProgress("Creating Table");
    Services.createTable().then((result){
      if('success' == result){
        //show a snackbar
        _showSnackBar(context,result);
        print("table created");
      }
      else{
        print("table not created");
      }
    });
  }

And this is the function calling code for adding an employee to the database

  _addEmployee(){
    if(_firstNameController.text.isEmpty || _lastNameController.text.isEmpty){
      print("Empty fields");
      return;
    }
    _showProgress("Adding Employee..");
    Services.addEmployee(_firstNameController.text, _lastNameController.text).then((result){
      if('success' == result){
        //
        print("success");
      }
      else{
        print("error");
      }
      _clearValues();
    });
  }

And this is the php file which contains all the response to the request recieved from the api and performing the requested crud operations

<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$table = "employee";

//we will get actions from the app to do operations in the database...
$action = $_POST['action'];

$conn = mysqli_connect($servername,$username,$password,$dbname);    
if(!$conn){
    //die("Connection Failed: ");
}
if(!mysqli_select_db($conn,"practice")){
   //echo "db not selected";
}

if("CREATE_TABLE" == $action){
    $sql = "CREATE TABLE IF NOT EXISTS ".$table."(
        id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        first_name VARCHAR(30) NOT NULL,
        last_name VARCHAR(30) NOT NULL
    )";
    if(mysqli_query($conn,$sql)){
        //echo "success";
    }
    else{
        //echo "failed";
    }
    mysqli_close($conn);
    return;
}


//add an employee
if("ADD_EMP" == $action){
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $sql = "INSERT INTO $table (first_name, last_name) VALUES ('$first_name','$last_name')";
    $result = mysqli_query($conn,$sql);
    //echo "success";
    mysqli_close($conn);
}


?>

Solution

  • static const ROOT = 'http://127.0.0.1/practice/service.php';
    

    127.0.0.1 is ip of the emulator or device itself which is loop back adress. the actual ip should be different