"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Efficiently Retrieve the Auto-Generated ID After an INSERT in PHP/MySQL?

How Can I Efficiently Retrieve the Auto-Generated ID After an INSERT in PHP/MySQL?

Posted on 2025-03-24
Browse:619

How Can I Efficiently Retrieve the Auto-Generated ID After an INSERT in PHP/MySQL?

Retrieving Inserted Row's ID in PHP/MySQL

One of the common tasks when working with MySQL databases is inserting a row and subsequently retrieving its auto-generated ID. This process involves two distinct queries, potentially introducing a time gap between inserting the row and fetching the ID, which can lead to race conditions.

Fortunately, PHP provides a straightforward solution to this issue: the mysqli_insert_id() function. The following code demonstrates its usage:

$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);

mysqli_insert_id() directly retrieves the ID generated by the most recent INSERT statement, eliminating the need for additional queries. This approach guarantees that the retrieved ID corresponds to the row just inserted.

An alternative method is to utilize MySQL's LAST_INSERT_ID() function within a single query. By combining multiple INSERT statements, it becomes possible to update several tables simultaneously and avoid the hassle of separate ID retrieval:

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

It's crucial to note that each MySQL connection maintains its own ID sequence, preventing potential conflicts between concurrent connections.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3