Sheldon
Sheldon

Reputation: 276

Get last inserted auto_incrementID MySQL using PHP

I try to get the last inserted auto_incremented ID after I execute a sqlstatement. I'm using the slim framework to do this. Here is my code:

$this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

...

$sql_stmt= "INSERT DELAYED INTO Tab(Id, Value1, Value2, Value3) VALUES (DEFAULT,?,?,?)";

$stmt= $this->conn->prepare($sql_stmt);
$stmt->bind_param("sss", $param1, $param2, $param3);
$stmt->execute();

This is what I try to return the incremented value:

return mysqli_insert_id($this->conn);
return $this->conn->mysqli_insert_id();
return $this->conn->insert_id;

But this doesn't work...

Does anybody know how to get the value?

Thanks for help!

Upvotes: 2

Views: 766

Answers (1)

exussum
exussum

Reputation: 18578

Your using INSERT DELAYED so its probably not even been inserted by the time you are calling that code.

When a client uses INSERT DELAYED, it gets an okay from the server at once, and the row is queued to be inserted when the table is not in use by any other thread.

and more specifically

Because the INSERT DELAYED statement returns immediately, before the rows are inserted, you cannot use LAST_INSERT_ID() to get the AUTO_INCREMENT value that the statement might generate. from

http://dev.mysql.com/doc/refman/5.5/en/insert-delayed.html

So dont use delayed if you want to get the ID.

Upvotes: 2

Related Questions