SyntaxStudy
Sign Up
PHP Intermediate 4 min read

PDO lastInsertId()

lastInsertId()

lastInsertId() returns the ID generated by the last INSERT for auto-increment columns. Call it immediately after execute().

Example
<?php
// Insert a post
$pdo->prepare("INSERT INTO posts (title, content, user_id) VALUES (?, ?, ?)")
    ->execute([$title, $content, $userId]);

$postId = (int) $pdo->lastInsertId();

// Now insert related tags using the new post ID
$stmt = $pdo->prepare("INSERT INTO post_tags (post_id, tag_id) VALUES (?, ?)");
foreach ($tagIds as $tagId) {
    $stmt->execute([$postId, $tagId]);
}

echo "Post {$postId} created with " . count($tagIds) . " tags";
Pro Tip

Cast lastInsertId() to int — it returns a string, and strict comparison may fail if you treat it as an integer.