phpmysqlmysqlilast-insert-idmysql-insert-id

MySQL SQL_INSERT_ID() and LAST_INSERT_ID do not work


I am using MySQL/PHP/Apache on a recent MacBook Pro, with all requests to localhost. I have searched but could not find a solution to my issue.

My PHP script successfully inserts a record into a basic main table whose primary key is named ID and is an Auto-Increment field, but it fails to capture the value of that ID for use with another INSERT into a different table when I try using LAST_INSERT_ID() or SQL_INSERT_ID(). The data needed for the second table need only that value and the contents of a text field from the same HTML form.

It is unmistakable that if I place an integer after the equals sign (as a test), my script works flawlessly (i.e. no error, and the script enters that required data into the second table perfectly). I have tried SQL_INSERT_ID() and LAST_INSERT_ID() with the same results: a completely white screen.

There are no foreign key constraints or anything complicated. This code fails and returns just a white screen:

$sql = "INSERT INTO Table1 
    (int1, str1, int2, int3, int4, int5) 
    VALUES (?, ?, ?, ?, ?, ?)";

if($stmt = mysqli_prepare($link, $sql)){
    mysqli_stmt_bind_param($stmt, "isiiii", 
        $param_int1, $param_str1, $param_int2, 
        $param_int3, $param_int4, $param_int5);
}

if(mysqli_stmt_execute($stmt)){
    $last_id = sql_insert_id();        // <--- problem statement
} else {
    echo "Something went wrong with the execution.";
}

But the code works exactly as I want it to when I use an integer in place of the function in question:

if(mysqli_stmt_execute($stmt)){
    $last_id = 6;
} else {
    echo "Something went wrong with the execution.";
}

The if(mysql_stmt_execute($stmt)) returns true if the first insert is successful, so it seems logical to initialize the variable $last_id right after that. Is this OK? Where else can I look in my code? Do I need to provide data inside the parentheses of the function?

MySQL version is 5.7.21 Mac OS X version 10.13.4

I consider myself an advancing beginner with PHP/MySQL. Any help would be greatly appreciated.


Solution

  • Try

    mysqli_insert_id($link);
    

    I think you are confusing the OOP and the procedural parts of the library or something.

    Because if I remember right sql_insert_id is from the now defunct mysql_* library.

    https://www.w3schools.com/php/func_mysqli_insert_id.asp