Home > Database > Mysql Tutorial > How to Retrieve the Last Inserted ID in MySQL using PHP?

How to Retrieve the Last Inserted ID in MySQL using PHP?

Mary-Kate Olsen
Release: 2024-12-20 09:46:11
Original
203 people have browsed it

How to Retrieve the Last Inserted ID in MySQL using PHP?

Retrieving the Last Inserted ID of a MySQL Table in PHP

When working with database tables that require frequent data insertion, retrieving the most recent ID inserted becomes necessary. PHP offers multiple options to address this need, depending on the database extension used.

Using PDO

The PHP Data Objects (PDO) extension provides a modern and efficient way to interact with databases. To obtain the last inserted ID using PDO, utilize the PDO::lastInsertId method.

Example:

$pdo = new PDO("mysql:host=localhost;dbname=database", "username", "password");

// Insert a new record
$stmt = $pdo->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
$stmt->execute([$value1, $value2]);

// Retrieve the last inserted ID
$lastInsertedId = $pdo->lastInsertId();
Copy after login

Using MySQLi

The MySQLi extension also offers a dedicated method for retrieving the last inserted ID. Use mysqli::$insert_id property to obtain this value.

Example:

$mysqli = new mysqli("localhost", "username", "password", "database");

// Insert a new record
$result = $mysqli->query("INSERT INTO table_name (column1, column2) VALUES ($value1, $value2)");

// Retrieve the last inserted ID
$lastInsertedId = $mysqli->insert_id;
Copy after login

Note for Older MySQL Extensions

While PDO and MySQLi are the recommended database extensions, it's worth mentioning that the deprecated mysql_ functions also offer the mysql_insert_id method. However, it's strongly advised to migrate to more modern extensions for improved security and performance.

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