How to save data to Two or More MySQL Table with a Single Query

Using mysqli_multi_query(), is it possible to retrieve the unique id for the row inserted in the first query, and use that to link the data inserted in the second query, or can that be done as part of the query / queries? If not, I’m struggling to see how it will be any use for the original requirement.

Yup.

I Created a foreign key in the 2nd table and linked the two tables together.

Then I used this query.

// attempt insert query execution
$sql = "INSERT INTO table1 (name, gender) VALUES ('$name', '$gender' ); 
INSERT INTO table2 (id, bike, car) VALUES (LAST_INSERT_ID(), '$bike', '$car' );
";

I was not using the last_insert_id and data was getting saved in only the first table.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.