Search code examples
phpmysqlprepared-statement

How to use both SELECT and INSERT query on single php prepared statement?


I am trying to insert a record and get the id of that record using a prepared statement. For that, I write a query "INSERT INTO ". $natureFlight ."(typeFlight, dateTimeSubmit, emb, acType, reg, companyName, callSign, dateFlight) VALUES (?,?,?,?,?,?,?,?); SELECT LAST_INSERT_ID();" which works fine in MySQL console but doesn't work using a prepared statement. If I remove the SELECT LAST_INSERT_ID(); from the query then it can insert record using a prepared statement.

I search for the solution and I found this but does not work for me.

Here is a code

$natureFlight = $_POST['selectedNatureFlight'];
$typeFlight = $_POST['selectedTypeFlight'];
$dateTimeSubmit = $_POST['dateTime'];
$emb = $_POST['emb'];
$acType = $_POST['acType'];
$reg = $_POST['reg'];
$companyName = $_POST['companyName'];
$callSign = $_POST['callSign'];
$dateFlight = $_POST['dateFlight'];

$insertRecord = "INSERT INTO ". $natureFlight ."(`typeFlight`, `dateTimeSubmit`, `emb`, `acType`, `reg`, `companyName`, `callSign`, `dateFlight`) VALUES (?,?,?,?,?,?,?,?); SELECT LAST_INSERT_ID();";
$stmt = $conn->prepare($insertRecord);
$stmt->bind_param("ssssssss", $typeFlight, $dateTimeSubmit, $emb, $acType, $reg, $companyName, $callSign, $dateFlight);
if($stmt->execute()){
    $stmt->bind_result($id);
    while($stmt->fetch()) {
         echo $id;
        }           
} else{
    $res['error'] = true;
    $res['message'] = $stmt->error;
}

After I run this I get an error

Fatal error: Uncaught Error: Call to a member function bind_param() on bool in
D:\xampp\htdocs\test\proc\flightPDF\src\body\user\records.php:40 Stack trace: #0 {main} thrown in 
D:\xampp\htdocs\test\proc\flightPDF\src\body\user\records.php on line 40

Line 40 contain $stmt->bind_param("ssssssss", $typeFlight, $dateTimeSubmit, $emb, $acType, $reg, $companyName, $callSign, $dateFlight);


Solution

  • You can't prepare multiple statements. That is why your prepare is failing and $stmt is a boolean (false). To fix it, remove the SELECT LAST_INSERT_ID() from your INSERT query and change the code to this, using insert_id to get the last insert id:

    $insertRecord = "INSERT INTO ". $natureFlight ."(`typeFlight`, `dateTimeSubmit`, `emb`, `acType`, `reg`, `companyName`, `callSign`, `dateFlight`) VALUES (?,?,?,?,?,?,?,?)";
    $stmt = $conn->prepare($insertRecord);
    $stmt->bind_param("ssssssss", $typeFlight, $dateTimeSubmit, $emb, $acType, $reg, $companyName, $callSign, $dateFlight);
    if (!$stmt) {
        $res['error'] = true;
        $res['message'] = $conn->error;
    }
    elseif ($stmt->execute()) {
        echo $conn->insert_id;
    } 
    else {
        $res['error'] = true;
        $res['message'] = $stmt->error;
    }