Home >Database >Mysql Tutorial >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);
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())");
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!