Jeewhizz
07-08-2003, 01:43 AM
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:
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf ("Last inserted record has id %d\n", mysql_insert_id());
?>
MySQL example from mysql.com (in the second insert, the ID is inserted in another table):
INSERT INTO foo (auto,text)VALUES(NULL,'text');
INSERT INTO foo2 (id,text)VALUES(LAST_INSERT_ID(),'text');
Links for more info and comments:
http://www.mysql.com/doc/en/Getting_unique_ID.html
http://www.php.net/mysql_insert_id
Created by: raf
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:
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf ("Last inserted record has id %d\n", mysql_insert_id());
?>
MySQL example from mysql.com (in the second insert, the ID is inserted in another table):
INSERT INTO foo (auto,text)VALUES(NULL,'text');
INSERT INTO foo2 (id,text)VALUES(LAST_INSERT_ID(),'text');
Links for more info and comments:
http://www.mysql.com/doc/en/Getting_unique_ID.html
http://www.php.net/mysql_insert_id
Created by: raf