William Kinaan William Kinaan - 3 months ago 21x
PHP Question

PDO get the last ID inserted

I have a query, and I want to get the last ID inserted. The field ID is the primary key and auto incrementing.

I know that I have to use this statement:


That statement works with a query like this:

$query = "INSERT INTO `cell-place` (ID) VALUES (LAST_INSERT_ID())";

But if I want to get the ID using this statement:


I get this error:

Fatal error: Call to undefined function LAST_INSERT_ID()

What am I doing wrong?


That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().


$stmt = $db->prepare("...");
$id = $db->lastInsertId();

If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:

$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetch(PDO::FETCH_NUM);
$lastId = $lastId[0];