MYSQL next increment value or last inserted value

Getting the next auto increment value and last inserted value from a mysql table are both two different things and should not be confused with one another. Next increment value should be the next id to be inserted and last inserted value is the last id inserted. Sometimes I see programmers using former code to get the latter task done and vice-versa. That might do it in some cases, but in the long run will surely fail.

Correct way of getting the value of next to be inserted id, is:

$query_autoinc 		= "SHOW TABLE STATUS LIKE 'table'";
$exec_autoinc 		= mysql_query($query_autoinc);
$row_autoinc 		= mysql_fetch_assoc($exec_autoinc);
$next_insert_id 	= $row_autoinc['Auto_increment'];

Correct way of getting the last inserted id, is:

$query_lastid 		= "select max(primary_key) as lastid from table";
$exec_lastid		= mysql_query($query_lastid);
$row_lastid 		= mysql_fetch_assoc($exec_lastid);
$last_inserted_id 	= $row_lastid['lastid'];
Abhishek Gupta
Follow me
Latest posts by Abhishek Gupta (see all)

Leave a Reply