How can the last inserted ID be utilized in PHP to insert data into another table after an INSERT operation?
To utilize the last inserted ID in PHP to insert data into another table after an INSERT operation, you can use the mysqli_insert_id() function to retrieve the ID generated by the last INSERT query. You can then use this ID in a subsequent INSERT query to insert data into another table that has a foreign key relationship with the first table.
// Perform the first INSERT query
mysqli_query($conn, "INSERT INTO table1 (column1) VALUES ('value1')");
// Get the ID of the last inserted row
$last_insert_id = mysqli_insert_id($conn);
// Use the last inserted ID in a second INSERT query to insert data into another table
mysqli_query($conn, "INSERT INTO table2 (table1_id, column2) VALUES ('$last_insert_id', 'value2')");
Related Questions
- Are there alternative identifiers, besides IP addresses, that can be used to uniquely identify guests in a PHP forum?
- What are the potential pitfalls of using the provided PHP login script?
- What are common reasons for the error message "Warning: main() failed to create stream: No such file or directory" in PHP?