Home >Database >Mysql Tutorial >How to Retrieve the Last Inserted ID Using PDO?

How to Retrieve the Last Inserted ID Using PDO?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-16 12:35:15790browse

How to Retrieve the Last Inserted ID Using PDO?

Retrieving the Last Inserted ID with PDO

In PDO, obtaining the ID of the last inserted row is an important task that arises frequently. Let's delve into the issue presented in the question and explore how to effectively accomplish this.

The problem arises when attempting to use the LAST_INSERT_ID() function as a direct PHP call. This results in an error, as LAST_INSERT_ID() is not a PHP function.

The solution lies in utilizing the PDO::lastInsertId() method. Here's an example of how to use it:

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

This method will return the ID of the last inserted row for the specified $db connection.

If you prefer to use SQL directly, you can retrieve the last inserted ID using a simple SELECT query:

$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();

This query will return the last inserted ID as the first column of the resulting row.

Whether you opt for the PDO::lastInsertId() method or the direct SQL query approach, both methods effectively retrieve the ID of the last inserted record.

The above is the detailed content of How to Retrieve the Last Inserted ID Using PDO?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn