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!