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.
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():
How to get the last inserted ID using PDO in PHP?
<?php
$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();
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Learn object oriented PHP</div>
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:
Example of specifying the name of a sequence object as an argument to PDO::lastInsertId() to get the last ID inserted in PHP
<?php
$lastId = $pdo->lastInsertId('sequence_name');