PHP Reference ยท Databases (PDO)
PHP PDO::lastInsertId() method
Reference for PHP PDO::lastInsertId(): read the auto-generated ID of the last inserted row, what it returns for batches and failed inserts, and PostgreSQL sequences.
PDO::lastInsertId() returns the ID that the database generated for the most recent insert on this connection, typically the value of an AUTO_INCREMENT (MySQL) or INTEGER PRIMARY KEY (SQLite) column. You call it right after the INSERT so you can save the new row's ID, redirect to its page or insert related rows.
The result is always a string, because some databases use IDs that do not fit in a PHP integer. Cast it with (int) when you know it is numeric.
$stmt = $pdo->prepare('INSERT INTO post (title) VALUES (?)'); $stmt->execute([$title]); $id = (int) $pdo->lastInsertId();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
PDO::lastInsertId(?string $name = null): string|false
| Name | Description |
|---|---|
$name |
Optional. Needed by drivers that use named sequences, mainly PostgreSQL ('orders_id_seq'). MySQL and SQLite ignore it. |
Return value: the last generated ID as a string. If nothing has been inserted on the connection yet, SQLite returns "0". Some drivers return false or throw when they do not support the feature.
Errors / Exceptions: PDOException (in exception mode) if the driver cannot provide the value, for example when the sequence name is wrong or missing on PostgreSQL.
Usage notes
- Call it right after the insert, on the same connection. The value is per connection, so another request cannot change it. It is safe under concurrency.
- Cast to
intwhen the column is an integer; keep it a string for UUID-like or very large IDs. - Batch inserts. After a multi-row
INSERT ... VALUES (...), (...), MySQL returns the ID of the first row, SQLite the ID of the last. Insert rows one at a time if you need every ID. - Only inserts count.
UPDATE,DELETE, failed inserts and ignored inserts leave the value unchanged. - Tables without an auto-generated key (you supply the ID yourself) give a meaningless result; use the ID you already have.
- PostgreSQL: pass the sequence name, or use
INSERT ... RETURNING idand fetch it like a normal result, which works in every driver that supports it, including SQLite 3.35+. - Transactions. The value is available inside a transaction. If you roll back, the ID is gone, and the database may skip that number.