{
    "slug": "pdo_lastinsertid",
    "term": "PDO lastInsertId()",
    "category": "php",
    "difficulty": "beginner",
    "short": "Returns the auto-increment ID generated by the most recent INSERT statement.",
    "long": "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.",
    "aliases": [
        "PDO lastInsertId",
        "auto increment ID PHP",
        "getLastInsertId"
    ],
    "tags": [
        "php",
        "database",
        "pdo"
    ],
    "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'."
    ],
    "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."
    ],
    "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'."
    ],
    "related": [
        "pdo",
        "pdo_transactions",
        "prepared_statement"
    ],
    "prerequisites": [
        "pdo",
        "mysql_auto_increment"
    ],
    "refs": [
        "https://www.php.net/manual/en/pdo.lastinsertid.php"
    ],
    "bad_code": "// Wrong — called on statement, not connection\n$stmt->execute([$userId, $total]);\n$orderId = $stmt->lastInsertId(); // Fatal error — method doesn't exist on PDOStatement",
    "good_code": "$stmt = $pdo->prepare('INSERT INTO orders (user_id, total) VALUES (?, ?)');\n$stmt->execute([$userId, $total]);\n$orderId = (int) $pdo->lastInsertId(); // cast to int for type safety\n\n// Now use $orderId for line items\n$itemStmt = $pdo->prepare('INSERT INTO order_items (order_id, product_id, qty) VALUES (?, ?, ?)');\nforeach ($items as $item) {\n    $itemStmt->execute([$orderId, $item['id'], $item['qty']]);\n}",
    "quick_fix": "Call $pdo->lastInsertId() immediately after execute() on an INSERT statement — before any other query",
    "effort": "low",
    "created": "2026-03-31",
    "updated": "2026-03-31",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/pdo_lastinsertid",
        "html_url": "https://codeclaritylab.com/glossary/pdo_lastinsertid",
        "json_url": "https://codeclaritylab.com/glossary/pdo_lastinsertid.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[PDO lastInsertId()](https://codeclaritylab.com/glossary/pdo_lastinsertid) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/pdo_lastinsertid"
            }
        }
    }
}