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:

1
2
3
4
$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:

1
2
3
4
$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'];
Follow me

Abhishek Gupta

I am Abhishek from Lucknow (India). I have been working as a software engineer from last 6+ years, and its my passion to learn new things and implement them as a practice.
Follow me

Latest posts by Abhishek Gupta (see all)

Leave a Reply