Home > Backend Development > PHP Tutorial > How Can I Get the ID of a Newly Inserted Row in MySQL Using PHP?

How Can I Get the ID of a Newly Inserted Row in MySQL Using PHP?

Susan Sarandon
Release: 2024-12-05 05:28:10
Original
890 people have browsed it

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";
Copy after login

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())");
Copy after login

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!

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