Home > Archive > PHP SQL > May 2005 > insert in 2 tables & get value from 1st in 2nd
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
insert in 2 tables & get value from 1st in 2nd
|
|
|
| Hi,
I want to insert values in 2 tables from a form, but in the second table, I
want to get the (new) id (auto_incr) of the first table in one of the column
in 2nd table.
Is it at all possible and how to do this if possible?
Thanks.
Ashok.
| |
|
|
Do this in 3 steps...
(1) INSERT into the first table.
(2) Use SELECT LAST_INSERT_ID() to get the value of the auto-increment
column in the new record.
(3) INSERT into the second substuting in the value from step (2).
Example (error checking omitted):
// (1)
mysql_query( 'INSERT INTO TABLE_1 VALUES ( "aaa", "bbb" )',
$SQLConnection );
// (2)
$res = mysql_query( 'SELECT LAST_INSERT_ID() AS "ID"',
$SQLConnection );
$row = mysql_fetch_array( $res, MYSQL_ASSOC );
$newid = $t_datRow[ "ID" ];
// (3)
mysql_query( 'INSERT INTO TABLE_2 VALUES ( ' . $newid . ', "ccc" )',
$SQLConnection );
---
Steve
| |
| Vincent THOREL 2005-05-29, 8:56 pm |
| Ashok wrote:
> Hi,
> I want to insert values in 2 tables from a form, but in the second table, I
> want to get the (new) id (auto_incr) of the first table in one of the column
> in 2nd table.
> Is it at all possible and how to do this if possible?
>
> Thanks.
> Ashok.
>
>
BEGIN TRANSACTION;
INSERT INTO table1 VALUES (...);
INSERT INTO5 table2 VALUES (LAST_INSERT_ID(), ...);
COMMIT;
|
|
|
|
|