Home > Backend Development > PHP Tutorial > How to Retrieve the Last Inserted ID in MySQLi and Use It for Another Table Insertion?

How to Retrieve the Last Inserted ID in MySQLi and Use It for Another Table Insertion?

Linda Hamilton
Release: 2024-12-07 20:43:20
Original
957 people have browsed it

How to Retrieve the Last Inserted ID in MySQLi and Use It for Another Table Insertion?

Retrieve Last Insert ID and Use It to Insert into Another Table with MySQLi

To insert a record into another table while associating it with the last inserted ID from a different table, you need to follow these steps:

Create an Auto-Increment Field

Ensure you have an auto-increment field in your primary key column to track the most recently inserted record's ID.

Retrieve Last Insert ID

Use the mysqli_insert_id() function to retrieve the last inserted ID from the first table. This ID will be used to link to the newly inserted record in the second table:

$last_id = mysqli_insert_id($conn);
Copy after login

Prepare Statement

Create a prepared statement that will insert the necessary data into the second table, including the association with the last inserted ID:

$stmt = $mysqli->prepare("
  INSERT INTO table1 (username, firstname, lastname, image) 
  SELECT ?,?,?,? FROM table2 t2 WHERE username = ? AND t2.id = ? 
");
Copy after login

Bind Parameters

Bind the parameters as usual, including the $image parameter with the value of the last inserted ID:

$stmt->bind_param('sssss', $username, $fname, $lname, $last_id, $username);
Copy after login

Execute Statement

Execute the prepared statement to insert the data into the second table:

$stmt->execute();
Copy after login

By following these steps, you can successfully retrieve the last inserted ID from one table and insert the record into another table while associating the data correctly.

The above is the detailed content of How to Retrieve the Last Inserted ID in MySQLi and Use It for Another Table Insertion?. 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