William Kinaan William Kinaan - 4 months ago 26
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:

LAST_INSERT_ID()


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:

$ID = LAST_INSERT_ID();


I get this error:

Fatal error: Call to undefined function LAST_INSERT_ID()


What am I doing wrong?

Answer

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

Like:

$stmt = $db->prepare("...");
$stmt->execute();
$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];