Search code examples
phpmysqlmysql-insert-id

Best way to find the last inserted ID in mysql using php


Im wondering as to what the best solution is to get the last inserted ID after a mysql inquiry?

I have found the following solutions :

<?php
function get_current_insert_id($table)
{
    $q = "SELECT LAST_INSERT_ID() FROM $table"; 
    return mysql_num_rows(mysql_query($q)) + 1;
}
?>

or even using mysql_insert_id php function, but apparently this function will not work well with bigint (thats what I am using for ID field) and if there are alot of consecutive sql inquiries it could be unreliable.

Could someone provide a reliable and fast solution to achieve this task?


Solution

  • Isn't SELECT LAST_INSERT_ID() reliable and safe enough?

    From MySQL Doc: The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own.

    Note from a forum: (...)All bets are off, though, if for some reason you are using persistent connections, such as via mysql_pconnect()(...)