Results 1 to 4 of 4
  1. #1
    Join Date
    Mar 2004
    Posts
    1,301

    return mysql_insert_id()

    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!

    Code:
    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");

  2. #2
    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:

    PHP Code:
    $query mysql_query("SELECT LAST_INSERT_ID() as last_id"); 
    Dyslexics Have More Fnu

  3. #3
    Join Date
    Nov 2005
    Location
    Palma de Mallorca, Spain
    Posts
    259
    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

  4. #4
    Join Date
    Mar 2004
    Posts
    1,301
    Thank you, Maxymizer and juanqake!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •