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
Release: 2024-12-16 05:48:18
Original
589 people have browsed it

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();
Copy after login

Solution with SQL:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template