lastInsertId()
lastInsertId() returns the ID generated by the last INSERT for auto-increment columns. Call it immediately after execute().
lastInsertId() returns the ID generated by the last INSERT for auto-increment columns. Call it immediately after execute().
<?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";
Cast lastInsertId() to int — it returns a string, and strict comparison may fail if you treat it as an integer.