Ahoura Ghotbi
Ahoura Ghotbi

Reputation: 2896

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?

Upvotes: 5

Views: 8080

Answers (2)

Romil Kumar Jain
Romil Kumar Jain

Reputation: 20775

If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only. The reason for this is to make it possible to reproduce easily the same INSERT statement against some other server.

Upvotes: 4

Related Questions