Getting the primary key value of the record that was last inserted by a user.
Often, we need to insert a new record in a table with an autonumber variable as primary key, and get the value of the automatically generated primary key back. For instance, when we start a new session for a user, and we need the sessionID to insert as a foreign key into an order table or so.
There are two function that return this value:
mysql_insert_id()--> PHP function
LAST_INSERT_ID()--> MySQL function that can be used by PHP and other Languages or in MySQL command line interface or MySQL front-end
PHP example from php.net:
MySQL example from mysql.com (in the second insert, the ID is inserted in another table):PHP Code:
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf ("Last inserted record has id %d\n", mysql_insert_id());
INSERT INTO foo (auto,text)VALUES(NULL,'text');
INSERT INTO foo2 (id,text)VALUES(LAST_INSERT_ID(),'text');
Links for more info and comments:
Created by: raf