Web Hosting Talk







View Full Version : return mysql_insert_id()


orbitz
12-07-2006, 01:32 AM
Would the result of getting mysql_insert_id() of the last insert be unpredictable if there are many users insert data to the same table at about the same time?

Should I use Lock table or something like this to make sure that each user get his correct insert id?

Thanks!


mysql_query("LOCK TABLES users WRITE");
mysql_query("SET AUTOCOMMIT = 0");

$sql = "INSERT INTO `users` (`organization`,`title`) VALUES ('$organization','$title')";
mysql_query($sql) or die (mysql_error());

$last_inserted_id = mysql_insert_id();

mysql_query("COMMIT");
mysql_query("UNLOCK TABLES");

maxymizer
12-07-2006, 01:55 AM
You need to pass link identifier parameter to mysql_insert_id(). It's safe to use it but there is an exception - if you use bigint as your type for auto_increment column. If the last inserted id has larger value than the int type can hold, the value you'll get will be incorrect. Instead, you should use internal MySQLs' query for obtaining last inserted id:


$query = mysql_query("SELECT LAST_INSERT_ID() as last_id");

juangake
12-07-2006, 07:47 AM
Maxymizer is right.

I would add (from the MySQL manual regarding LAST_INSERT_ID()):
"The ID generated is maintained in the server on a per-connection basis", so you don't have to worry about simultaneous connections. The LAST_INSERT_ID() gives you the ID you want for the last INSERT on your connection.

Regards,

Juan

orbitz
12-07-2006, 03:41 PM
Thank you, Maxymizer and juanqake!