Page 1 of 1
Getting INSERTed values
Posted: Thu Apr 19, 2007 3:12 am
by MarkAshley
Is it possible for mysql_query("INSERT INTO.....") to return the values in the record it inserted? For example, lets say I have a table "table1" with primary key "id" and column "col1", can I do the following:
Code: Select all
$result=mysql_query("INSERT INTO table1 VALUES(null,'value')");
then retrieve the value of the primary key for the row it has just inserted? I don't want to use a SELECT statement to retrieve the row as it may be possible for another user to enter the same value on a different row.
TIA
Mark
Posted: Thu Apr 19, 2007 4:02 am
by MarkAshley
Ahhh, just found mysql_insert_id() linked from the PHP document on mysql_query(). According to the document:
int mysql_insert_id ( [resource $link_identifier] )
Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query
I'll give it a try.
Cheers
Mark
Posted: Thu Apr 19, 2007 4:07 am
by MarkAshley
Confirming for others who may find this thread searching for the same thing: mysql_insert_id() works. In this example the first column is the PK:
Code: Select all
mysql_query("INSERT INTO table1 VALUES(NULL,'value1')");
$id=mysql_insert_id();
$id now contains the PK of the row which was just inserted.
Posted: Thu Apr 19, 2007 5:07 am
by JayBird
Yep, well done. Thats the way to do it.
Thanks for updating your thread with an answer too!