PHP MySQL Get Last ID
In this page:
mysqli_query($conn, "INSERT INTO table_name (column1) VALUES ('value')");
$id = mysqli_insert_id($conn); // AUTO_INCREMENT id of the new row
Getting the ID of a Newly Inserted Row
Immediately after a successful INSERT into a table with an AUTO_INCREMENT primary key, mysqli_insert_id($conn) returns exactly the ID value MySQL generated for that new row -- no separate SELECT query needed.
Example: Getting the ID of a Newly Inserted Row
<?php
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE orders (id INTEGER PRIMARY KEY AUTOINCREMENT, item TEXT)");
$db->exec("INSERT INTO orders (item) VALUES ('Book')");
echo $db->lastInsertRowID(); // mysqli_insert_id($conn) in MySQL
?>
Login to try C/C++/Java/PHP code in the editor
Using the New ID to Insert a Related Row
A very common pattern is inserting a parent row (like an order), capturing its new ID with mysqli_insert_id(), and then using that ID immediately to insert related child rows (like order items) that reference it via a foreign key.
Example: Using the New ID to Insert a Related Row
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE orders (id INTEGER PRIMARY KEY AUTOINCREMENT)");
$db->exec("CREATE TABLE items (order_id INTEGER, product TEXT)");
$db->exec("INSERT INTO orders DEFAULT VALUES");
// Declare `$orderId`, set to `$db->lastInsertRowID()`
$orderId = $db->lastInsertRowID();
$db->exec("INSERT INTO items (order_id, product) VALUES ($orderId, 'Pen')");
// Print "Linked item to order #$orderId" to the output
echo "Linked item to order #$orderId";
?>
Login to try C/C++/Java/PHP code in the editor
When mysqli_insert_id() Returns 0
mysqli_insert_id() returns 0 if the most recent query was not an INSERT into an auto-increment column -- like an UPDATE, a SELECT, or an insert into a table with no auto-increment primary key at all -- which is worth checking for if your code assumes an ID was always generated.
Example: When mysqli_insert_id() Returns 0
<?php
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)");
$db->exec("INSERT INTO users (name) VALUES ('Alice')");
$db->exec("UPDATE users SET name = 'Alicia' WHERE id = 1");
echo $db->lastInsertRowID(); // still 1 in SQLite, but mysqli_insert_id() returns 0 after a non-insert query
?>
Login to try C/C++/Java/PHP code in the editor
Getting the Last ID with PDO Instead
PDO, PHP's other database abstraction layer, offers the equivalent functionality through $pdo->lastInsertId(), called the same way -- immediately after the relevant insert, on the same PDO connection object.
Example: Getting the Last ID with PDO Instead
<?php
// Create a new `PDO` instance with 'sqlite::memory:', stored in `$pdo`
$pdo = new PDO('sqlite::memory:');
$pdo->exec("CREATE TABLE orders (id INTEGER PRIMARY KEY AUTOINCREMENT, item TEXT)");
$pdo->exec("INSERT INTO orders (item) VALUES ('Book')");
// Print `$pdo->lastInsertId()` to the output
echo $pdo->lastInsertId();
?>
Login to try C/C++/Java/PHP code in the editor
Common Uses for the New ID
Beyond linking related rows, the newly inserted ID is often used to redirect a user to a detail page for the record they just created (like /orders/42), to build a confirmation message, or to return the ID as part of a JSON API response after a successful create operation.
Example: Common Uses for the New ID
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE orders (id INTEGER PRIMARY KEY AUTOINCREMENT, item TEXT)");
$db->exec("INSERT INTO orders (item) VALUES ('Book')");
// Declare `$id`, set to `$db->lastInsertRowID()`
$id = $db->lastInsertRowID();
// Print `json_encode(["status" => "created", "order_id" => $id])` to the output
echo json_encode(["status" => "created", "order_id" => $id]);
?>
Login to try C/C++/Java/PHP code in the editor
- Calling mysqli_insert_id() long after other queries have run, when it only reliably reflects the ID from the most recent successful insert on that same connection.
- Assuming mysqli_insert_id() works for tables without an AUTO_INCREMENT column -- it only has a meaningful value for inserts into such a column.
- Using mysqli_insert_id() in a context involving multiple concurrent connections and expecting it to somehow return another connection's last insert ID.
- mysqli_insert_id($conn) returns the auto-increment ID generated by the most recent INSERT on that specific connection.
- It must be called immediately after the relevant INSERT, before any other query runs on the same connection.
- It returns 0 if the last query did not generate a new auto-increment value.
mysqli_insert_id() has been part of the mysqli extension since PHP 5, replacing the older mysql_insert_id() function.
Chapter Quiz — Complete all 21 topics to unlock
0/21 topics done
Complete these topics first:
- PHP MySQL Introduction
- PHP MySQLi Connection
- PHP PDO Introduction
- PHP CRUD Operations
- PHP Prepared Statements
- PHP Stored Procedures
- PHP Transactions
- PHP Error Handling in DB
- PHP MySQL Connect
- PHP MySQL Create DB
- PHP MySQL Create Table
- PHP MySQL Insert Data
- PHP MySQL Get Last ID
- PHP MySQL Insert Multiple
- PHP MySQL Prepared Statements
- PHP MySQL Select Data
- PHP MySQL Where
- PHP MySQL Order By
- PHP MySQL Delete Data
- PHP MySQL Update Data
- PHP MySQL Limit Data