Search code examples
phpmysqliauto-increment

How to use mysqli_insert_id with prepared statements?


I have the following code and I'm getting crazy with calling an auto_increment id

$sql = "INSERT INTO tablename (x1, x2) VALUES(?,?)";
if($query = $db->prepare($sql)){
$query->bind_param('ss', $x1, $x2);
$query->execute();

$id = mysqli_insert_id($query);

For a reason I don't know why this is not working. I also tried

$id = mysqli_insert_id($sql);

And

$id = mysqli_insert_id();

I just decided to work with mysqli. Before that, I only used MySQL where I had no problem with

$id = mysql_insert_id();

Solution

  • Probably something like

    $query->commit(); OR $query->close();