Home > Database > Mysql Tutorial > How to Retrieve the Last Inserted ID in PHP/MySQL After an INSERT Query?

How to Retrieve the Last Inserted ID in PHP/MySQL After an INSERT Query?

Susan Sarandon
Release: 2024-12-23 18:14:15
Original
160 people have browsed it

How to Retrieve the Last Inserted ID in PHP/MySQL After an INSERT Query?

Retrieving the Last Inserted 'id' after Database Insertion Using PHP/MySQL

To insert a row into a MySQL table and retrieve its auto-incremented 'id' field, you can utilize the mysqli_insert_id() function. Here's how it can be implemented in PHP:

$link = mysqli_connect('127.0.0.1', 'my_user', 'my_pass', 'my_db');
mysqli_query($link, "INSERT INTO mytable (1, 2, 3, 'blah')");
$id = mysqli_insert_id($link);
Copy after login

By using mysqli_insert_id(), you can retrieve the ID of the last inserted row without needing to worry about any race conditions or duplicates.

Alternatively, you can also execute multiple queries in one go and use MySQL's LAST_INSERT_ID() method to modify multiple tables simultaneously:

mysqli_query($link, "INSERT INTO my_user_table ...;
  INSERT INTO my_other_table (`user_id`) VALUES (LAST_INSERT_ID())");
Copy after login

Note that each connection maintains its own ID, preventing conflicts.

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