Getting INSERTed values

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
MarkAshley
Forum Commoner
Posts: 34
Joined: Fri Nov 18, 2005 1:36 am

Getting INSERTed values

Post 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
MarkAshley
Forum Commoner
Posts: 34
Joined: Fri Nov 18, 2005 1:36 am

Post 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
MarkAshley
Forum Commoner
Posts: 34
Joined: Fri Nov 18, 2005 1:36 am

Post 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.
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post by JayBird »

Yep, well done. Thats the way to do it.

Thanks for updating your thread with an answer too!
Post Reply