Home > Mobile >  how to get insert id from php api in flutter app?
how to get insert id from php api in flutter app?

Time:12-10

I am working on a flutter app which simply updates and inserts the data into a table I have create a php API script:

if("Sign_Up"==$action){
  
    $email = mysqli_real_escape_string($connect, $_POST['email']);
    $phone = mysqli_real_escape_string($connect, $_POST['phone']);

    $query = "INSERT INTO driver_details (phone, email)
              VALUES('$phone', '$email')";
    $results = mysqli_query($connect, $query);
    if($results>0)
    {
        echo "user added successfully";
    }
 }

and I post the data to the API using this data:

static const ROOT="https://www.example.com/driverapp-apis";
static const _Sign_Up='Sign_Up';

Future signup() async {

var response = await http.post(Uri.parse(ROOT), body: {
    "email": emailController.text,
    "action":'Sign_Up',
    "phone":phoneController.text,
    });
}

and I **am able to sccessfully insert data ** what I want to get the insert id of this query and use it for further update ? so anyone can help me how to get insert id into my flutter app?

CodePudding user response:

Try to encode request body

Map body = {
  "email": emailController.text,
  "action":'Sign_Up',
  "phone":phoneController.text,
};

Future signup() async {

var response = await http.post(Uri.parse(ROOT), body: jsonEncode(body));
}

CodePudding user response:

Not sure about the Flutter end, but you can get the insert_id from the mysql insert like this, and then return it to the flutter/dart code for you to deal with as you wish

I also removed the SQL Injection issue

if("Sign_Up"==$action){
  
    $query = "INSERT INTO driver_details (phone, email)
              VALUES(?,?)";
    $stmt = $connect->prepare($sql);
    $stmt->bind_param('ss', $_POST['phone']
                            $_POST['email'] );
    $result = $stmt->execute();
    // successful execution of an insert returns a TRUE and a failure returns FALSE
    if($results) {
        // pass back the new id and the message as a json string
        $res = ['id' => $connect->insert_id,
                'msg' => "user added successfully"
                'status' => 1];
        echo json_encode($res);
    } else {
        echo json_encode(['msg' => 'user not added',
                          'status' => 99]);
    }
}
  • Related