Home >Backend Development >PHP Tutorial >How Can I Get the ID of a Newly Inserted Row in MySQL Using PHP?
Inserting a Row into a MySQL Table and Retrieving Its ID
When inserting a row into a MySQL table with an auto-incrementing ID field, obtaining the ID of the inserted row can be crucial. However, the time interval between the insertion and ID retrieval can introduce potential errors.
The mysqli_insert_id() Function
The PHP function mysqli_insert_id() provides a solution to this problem. After executing an INSERT query, mysqli_insert_id() returns the ID of the last inserted row in the current connection. This eliminates the need for querying the database again or relying on race conditions.
Example 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); echo "Inserted Row ID: $id";
Alternative Approach: Combining Queries
Alternatively, MySQL's LAST_INSERT_ID() method can be used to modify multiple tables in a single query while assigning unique IDs:
mysqli_query($link, "INSERT INTO my_user_table ...; INSERT INTO my_other_table (`user_id`) VALUES (LAST_INSERT_ID())");
Note: Each MySQL connection maintains a separate ID tracker, preventing ID conflicts.
The above is the detailed content of How Can I Get the ID of a Newly Inserted Row in MySQL Using PHP?. For more information, please follow other related articles on the PHP Chinese website!