How to get the last ID inserted with PDO and PHP?

Spread the love

Sometimes, we want to get the last ID inserted with PDO and PHP.

In this article, we’ll look at how to get the last ID inserted with PDO and PHP.

How to get the last ID inserted with PDO and PHP?

To get the last ID inserted with PDO and PHP, we can use the lastInsertId method.

For instance, we write

$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();

to create a prepared statement object with $db->prepare called with a insert statement SQL string.

Then we call execute to run the statement.

Next, we call $db->lastInsertId to return the ID of the last inserted entry.

Conclusion

To get the last ID inserted with PDO and PHP, we can use the lastInsertId method.

Leave a Reply

Your email address will not be published.