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

PDO lastInsertId()

PHP PHP 5.1+ Beginner
debt(d7/e1/b1/t5)
d7 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'only careful code review or runtime testing' (d7). The detection_hints note a code_pattern ($stmt->lastInsertId()) that could be caught by static analysis, but the subtler misuses — calling after a second query, or on a table without AUTO_INCREMENT — produce no error and silently return '0' or a stale ID. These pass through PHP without complaint and require careful code review or test-driven discovery.

e1 Effort Remediation debt — work required to fix once spotted

Closest to 'one-line patch or single-call swap' (e1). The quick_fix is explicit: replace $stmt->lastInsertId() with $pdo->lastInsertId() and place it immediately after execute(). This is a single-line substitution with no structural change required.

b1 Burden Structural debt — long-term weight of choosing wrong

Closest to 'minimal commitment' (b1). PDO lastInsertId() is a localised point-of-use call tied to specific INSERT operations. It imposes no architectural commitment, no cross-cutting concern, and no ongoing maintenance tax on future maintainers beyond knowing where to call it.

t5 Trap Cognitive debt — how counter-intuitive correct behaviour is

Closest to 'notable trap' (t5). The primary misconception — that lastInsertId() returns an integer when it always returns a string — is a documented gotcha that causes bugs in strict type comparisons. The wrong-object trap ($stmt vs $pdo) is also common. These are well-known pitfalls developers encounter and learn, placing this at t5.

About DEBT scoring →

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 39
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
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 2 pings F 2 pings S 2 pings S 1 ping M 0 pings T 1 ping W 0 pings T 1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 1 ping S 0 pings S 0 pings M 1 ping T 0 pings W
No pings yet today
SEMrush 1
Perplexity 6 Google 5 Scrapy 5 Unknown AI 3 Ahrefs 3 Meta AI 2 Claude 2 ChatGPT 1 Majestic 1 PetalBot 1 SEMrush 1
crawler 26 crawler_json 3 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