Home >Database >Mysql Tutorial >How to Retrieve the Last Inserted ID in MySQL using 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.
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();
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;
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!