Jump to content

[SOLVED] insert data into 3 tables at the same time


Recommended Posts

 

How could I insert data into 3 Mysql tables at the same time?

 

I have 3 tables table1 has an id field which is auto increment and a few other fields. I want to be able to insert data into this table and then retrieve the value from the id field and insert it into the other two tables along with the relevant data for the other fields.

 

I initially thought that this could be done in one query but when i searched for this the nearest I could find was saying to use left_join but I didnt understand how this worked.

 

thanks for any help

You will use 3 separate queries.

 

<?php

$query1 = "INSERT INTO table1 (field1,field2,field3) values ($value1,$value2,$value3)";

$lastId = mysql_insert_id(); 

$query2 = "INSERT INTO table2 (autoIdField,field4,field5,field6) values ($lastId,$field4,$field5)";

$query3 = "INSERT INTO table3 (autoIdField,field7,field8,field9) values ($lastId, $field7,$field8,$field9)";

?>

 

I think I forgot a few quotes and such, but the basic principle applies.

 

Nate

$lastId will contain the auto-increment id created in the first query.

 

 

 

 

<?php

$query1 = mysql_query("INSERT INTO table1 (field1,field2,field3) values ($value1,$value2,$value3)");

$lastId = mysql_insert_id(); 

$query2 = mysql_query("INSERT INTO table2 (autoIdField,field4,field5,field6) values ($lastId,$field4,$field5)");

$query3 = mysql_query("INSERT INTO table3 (autoIdField,field7,field8,field9) values ($lastId, $field7,$field8,$field9)");

?>

 

You need to also run mysql_query

You need to also run mysql_query()

 

hehehe.. I forgot that part didn't I.. I was just trying to illustrate the whole 3 separate queries and using mysql_insert_id()..... I guess I should have shown the mysql_query part too..

 

sorry about that.

 

Nate

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.