To retrieve the last inserted ID after an INSERT statement using PDO in PHP, you can use the lastInsertId()
method provided by PDO.
Here's an example of how to do it:
// Assuming you have already established a PDO connection
// Prepare the INSERT statement
$stmt = $pdo->prepare("INSERT INTO your_table (column1, column2) VALUES (:value1, :value2)");
// Bind the values
$stmt->bindValue(':value1', $value1);
$stmt->bindValue(':value2', $value2);
// Execute the INSERT statement
$stmt->execute();
// Retrieve the last inserted ID
$lastInsertedId = $pdo->lastInsertId();
// Use the last inserted ID
echo "Last inserted ID: " . $lastInsertedId;
In the example above, you first prepare the INSERT statement using the prepare()
method of PDO. Then, you bind the values to the placeholders in the statement using bindValue()
. After that, you execute the INSERT statement using execute()
. Finally, you retrieve the last inserted ID using $pdo->lastInsertId()
and assign it to the $lastInsertedId
variable for further use.