Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Putting Data into Two Tables 1

Status
Not open for further replies.

jsnull

IS-IT--Management
Feb 19, 2002
99
US
Reference this thread for a similar issue thread434-26323...

What is the current best recommended way to write data into two tables and can you provide an example of the syntax?

table1 has id, name, addresss
table2 has id, orders

table1.id and table2.id are the same.



Jim Null
[afro]
 
I would just do two SQL statements. Im sure it isn't the best way, but tis a solution...
Code:
$SQL = 'INSERT INTO `table1`(`id`,`name`,`address`)'; 
$SQL .=	"VALUES ('".$id."','".$name."','".$address."')";
$Result = mysql_query($SQL);

$SQL = 'INSERT INTO `table2`(`id`,`orders`)'; 
$SQL .=	"VALUES ('".$id."','".$orders."')";
$Result = mysql_query($SQL);
 
I would set up the column 'id' in the table 'table1' to be
an auto_increment column. That way, my script could issue the query:

[tt]mysql_query ("INSERT INTO table1 (name, address) VALUES ('a name', 'an address'");[/tt]

and let MySQL automatically generate the value for the 'id' column.

Then I would use the PHP function mysql_insert_id() to fetch the last-automatically-generted value (which would be the value for 'id' from my last insert -- it's designed to work that way). Let's store that value in $last_id:

[tt]$last_id = mysql_insert_id();[/tt]

I would then use that value in a second insert query:

[tt]mysql_query ("INSERT INTO table2 (id, orders) VALUES (" . $last_id . ", 'an order'");[/tt]





Want the best answers? Ask the best questions! TANSTAAFL!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top