Oj Obasi
Oj Obasi

I am also and will continue to be a student of web design and development. My tutorials may not be for you. If you feel that way, then search online for better tutorials.

PHP PDO Get ID of Last Inserted Data

There are so many reasons you may want to know the id of your last inserted row. In this tutorial, we will be adding a new record into our database table 'products' and we want to echo out the last inserted id.

We would be getting our last insert ID using lastInsertId().

<?php
require 'database.php'; // database connection
try{
$sql = "INSERT INTO products (product_name, category, price, date_added)
VALUES ('Blue Shirt', 'Shirts', '$100', now())";
// use exec() because no results are returned
$db->exec($sql);
$last_id = $db->lastInsertId(); // HERE IS YOUR LAST INSERT ID
echo "New record created successfully. Last inserted ID is: " . $last_id;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
?>

We assign our last Inserted ID to variable $last_id.