← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

PDO lastInsertId()

php PHP 5.1+ Beginner

Also Known As

PDO lastInsertId auto increment ID PHP getLastInsertId

TL;DR

Returns the auto-increment ID generated by the most recent INSERT statement.

Explanation

lastInsertId() must be called on the PDO connection object (not the statement) immediately after the INSERT. It returns a string, not an integer. In a transaction, it returns the last inserted ID even before commit(). With PostgreSQL, a sequence name must be passed as the argument. lastInsertId() returns '0' if the table has no AUTO_INCREMENT column or no row was inserted.

Watch Out

lastInsertId() returns '0' (string) if no row was inserted or the table has no AUTO_INCREMENT. Always check before using the value.

Common Misconception

lastInsertId() returns an integer. It always returns a string — cast to (int) if you need an integer for type-safe comparisons.

Why It Matters

Retrieving the generated ID immediately after INSERT is essential for linking related records — e.g. inserting an order and then inserting its line items using the new order ID.

Common Mistakes

  • Calling lastInsertId() on the statement object ($stmt->lastInsertId()) — it's a PDO method, not PDOStatement.
  • Calling it after a second query — it reflects the most recent INSERT on the connection.
  • Using it with tables that have no AUTO_INCREMENT column — returns '0'.

Avoid When

  • Do not call lastInsertId() after any query other than the INSERT you care about — it reflects the most recent INSERT on the connection.
  • Do not use with tables that have no AUTO_INCREMENT column — always returns '0'.

When To Use

  • Use immediately after an INSERT to retrieve the generated primary key for linking related records.
  • Use inside a transaction before commit() — the ID is available within the transaction.

Code Examples

✗ Vulnerable
// Wrong — called on statement, not connection
$stmt->execute([$userId, $total]);
$orderId = $stmt->lastInsertId(); // Fatal error — method doesn't exist on PDOStatement
✓ Fixed
$stmt = $pdo->prepare('INSERT INTO orders (user_id, total) VALUES (?, ?)');
$stmt->execute([$userId, $total]);
$orderId = (int) $pdo->lastInsertId(); // cast to int for type safety

// Now use $orderId for line items
$itemStmt = $pdo->prepare('INSERT INTO order_items (order_id, product_id, qty) VALUES (?, ?, ?)');
foreach ($items as $item) {
    $itemStmt->execute([$orderId, $item['id'], $item['qty']]);
}

Added 31 Mar 2026
Views 18
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
2 pings W 0 pings T 0 pings F 1 ping S 0 pings S 3 pings M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 1 ping S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 1 ping T 0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T
No pings yet today
No pings yesterday
Perplexity 6 Google 3 Unknown AI 3 ChatGPT 1 Meta AI 1 Ahrefs 1
crawler 13 crawler_json 1 pre-tracking 1
DEV INTEL Tools & Severity
⚙ Fix effort: Low
⚡ Quick Fix
Call $pdo->lastInsertId() immediately after execute() on an INSERT statement — before any other query
📦 Applies To
PHP 5.1+ web cli
🔗 Prerequisites
🔍 Detection Hints
$stmt->lastInsertId() — method called on statement not connection
Auto-detectable: ✓ Yes
🤖 AI Agent
Confidence: High False Positives: Low ✓ Auto-fixable Fix: Low Context: Line

✓ schema.org compliant