Take the 2-minute tour ×

Firstly please excuse my lack of knowledge for SQL, I have only done basic inserts before.

I am currently improoving a little system that I have, and I want to insert some data that is obtained via _GET (php) into two tables. My problem is as follows.

My first table (table_one) has an auto incrementing value called "id", which I need to obtain, and post over to my second table (table_two).

Because of the way data will be updated at the later date, the ID in table two, is a reference to the ID that is automatically generated upon insert in table one (hence no ID in the code below). (I will be using the ID in table one to do a for loop for each matching ID instance in table_two)

How can I run one query to update one table, then update the 2nd with the unique id obtained from the first table?

My current code is this...

INSERT INTO table_one (valueone,valuetwo,valuethee) VALUES ('$v1','$v2','$v3')
share|improve this question
add comment

3 Answers

up vote 5 down vote accepted

you can use mysql_insert_id() built in command of php this will give you the id of the recently inserted data

mysql_query("insert into.... ");
$a = mysql_insert_id();
share|improve this answer
Works brilliantly - thankyou! –  Graeme Leighfield Sep 21 '11 at 13:47
add comment

mysql_insert_id() after first query will give you id

I want to insert some data that is obtained via _GET

that's wrong. this data should be obtained via POST

share|improve this answer
add comment

Expanding on @Ujjwal's answer, you can do the same just using SQL.

INSERT INTO table1 (x,y) VALUES ('x','y');
INSERT INTO table2 (t1_id, z) VALUES (LAST_INSERT_ID(), 'z');

See: http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

share|improve this answer
add comment

Your Answer


