PDO get the last ID inserted

William Kinaan picture William Kinaan · May 21, 2012 · Viewed 230.5k times · Source

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

Corbin picture Corbin · May 21, 2012

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->fetchColumn();