Home >Database >Mysql Tutorial >How to Retrieve the Last Inserted ID to Populate Another Table?

How to Retrieve the Last Inserted ID to Populate Another Table?

Susan Sarandon
Susan SarandonOriginal
2024-12-14 01:45:10518browse

How to Retrieve the Last Inserted ID to Populate Another Table?

Retrieving Last Inserted ID to Populate Another Table

In your code snippet, you're attempting to retrieve the last inserted ID from one table and use it to insert data into another. However, the line where you assign the value to $image is incorrect. Here's how you can correctly retrieve the last inserted ID:

  1. Create an auto-increment field for the ID column in your first table.
  2. After inserting into the first table, you can use the mysqli_insert_id() function to retrieve the last inserted ID.
$image = mysqli_insert_id($mysqli);
  1. Update the code to use the correct variable for the image field:
$stmt = $mysqli->prepare("
  insert into table1 (username, firstname, lastname, image) 
  select ?,?,?,? from table2 t2 where username = ? and  t2.id = ? 
   ");
$stmt->bind_param('sssss', $username, $fname, $lname, $image, $username, $image);
$stmt->execute();

The above is the detailed content of How to Retrieve the Last Inserted ID to Populate Another Table?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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