lastInsertId())When inserting records into a table with an AUTO_INCREMENT primary key column, PDO provides $pdo->lastInsertId() to retrieve the automatically generated ID of the last inserted row.
lastInsertId() Architectureflowchart TD
A["Execute INSERT INTO Query"] --> B["MySQL Server Assigns Auto-Increment ID (e.g. 42)"]
B --> C["Call $pdo->lastInsertId()"]
C --> D["Returns '42' (String representing last primary key)"]
D --> E["Use New ID for Relational Child Records (e.g. order_items.order_id = 42)"]
<?php
declare(strict_types=1);
try {
$pdo = new PDO("mysql:host=127.0.0.1;dbname=ecommerce_db;charset=utf8mb4", 'root', 'secret_password', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
// 1. Insert Parent Order Record
$orderSql = "INSERT INTO orders (user_id, total_amount, status) VALUES (:user_id, :total, :status)";
$orderStmt = $pdo->prepare($orderSql);
$orderStmt->execute([
'user_id' => 101,
'total' => 149.99,
'status' => 'completed'
]);
// 2. Retrieve Auto-Incremented Order ID
$newOrderId = (int)$pdo->lastInsertId();
echo "Created Order Successfully! Assigned Order ID: #$newOrderId
";
} catch (PDOException $e) {
die("Transaction Error: " . $e->getMessage());
}
lastInsertId() Immediately After execute(): Retrieve the ID before executing any subsequent insert queries on the connection.(int): lastInsertId() returns a string representation of the integer ID; cast it to (int) when strict integer types are required.What PDO method returns the auto-increment ID generated by the most recent INSERT query? ($pdo->lastInsertId())
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.