Home >Backend Development >PHP Tutorial >How to Retrieve the Last Inserted ID in PHP Using PDO?

How to Retrieve the Last Inserted ID in PHP Using PDO?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-16 05:48:18599browse

How to Retrieve the Last Inserted ID in PHP Using PDO?

Retrieving the Last Inserted ID with PDO

Issue:

Many beginners face an error while attempting to retrieve the last inserted ID using LAST_INSERT_ID(), resulting in the fatal error "Call to undefined function LAST_INSERT_ID()." This error arises from the misconception that LAST_INSERT_ID() is a PHP function, when in reality it's an SQL function.

Solution with PDO:

The correct method to retrieve the last inserted ID using PDO is through the lastInsertId() method:

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

Solution with SQL:

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

The above is the detailed content of How to Retrieve the Last Inserted ID in PHP 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