PDO get the last ID inserted

To get the last inserted ID using PDO, you can use the PDO::lastInsertId() method after inserting a row into the database. This method returns the ID of the last inserted row, or the last value inserted into an AUTO_INCREMENT column.

Here is an example of how to use PDO::lastInsertId():


$pdo = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');

$sql = "INSERT INTO table_name (column1, column2, ...) VALUES (?, ?, ...)";
$stmt = $pdo->prepare($sql);
$stmt->execute([$value1, $value2, ...]);

$lastId = $pdo->lastInsertId();

Watch a course Learn object oriented PHP

Note that you must use prepared statements and execute the insert statement before calling PDO::lastInsertId().

You can also specify the name of a sequence object as an argument to PDO::lastInsertId() if you are using a database that supports sequences and you want to get the last inserted ID from a specific sequence. For example:


$lastId = $pdo->lastInsertId('sequence_name');