0

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);
}


?>
1
  • 127.0.0.1 is ip of the emulator or device itself. the actual ip should be different Commented Feb 7, 2020 at 12:14

2 Answers 2

2
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

Sign up to request clarification or add additional context in comments.

4 Comments

The actual problem was 127.0.0.1 and because my pc and emulator device are not connected on the same network then instead of port forwarding I've used my web hosting and it works.Thanks!
I'm just asking that is it a secure way like this to perform db operations or there is something more secure?
All services should be authenticated and authorized. You can use OAuth for the same.
or use json Web Token
-1

just put

final response = await http.post('http://192.168.100.17:80/getdata.php', body: map);

your machine ip and server port.

1 Comment

Please extend the answer so any reader can get more information on what the code does.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.