Absolutely Tech

Get Auto Increment value from MySQL table


Many a times we require the next Auto Increment value from a MySQL table. Most of the people would do something like this:

$query = "Select MAX(id) from users";
$res = mysql_query($query);
$row = mysql_fetch_assoc($res);
$maxid = $row['MAX(id)'];
echo $maxid;



This would give correct results but if we delete the latest row, it will start to give wrong results.



We’ve got another query which can be used to get correct ‘Auto Increment’ values from the table.

$query = "SHOW TABLE STATUS LIKE 'users'";
$res = mysql_query($query);
$row = mysql_fetch_assoc($res);
$maxid = $row['Auto_increment'];
echo $maxid;

This will always give correct values for Auto Increment.

Category: MySQL, PHP

Tagged: , , , ,

  • http://edo.webmaster.am/ Edvard Ananyan

    You can try this query instead:

    select auto_increment from information_schema.tables where table_schema = database() and table_name = 'table_name'

  • Deepak Mittal

    Thats an alternative too.

  • JR

    This is giving me two rows where the second one is correct and the first one is not.
    what could the problem be?

  • JR

    This is giving me two rows where the second one is correct and the first one is not.
    what could the problem be?

  • http://www.techmindz.com Deepak Mittal

    Did you try running the query directly through phpmyadmin? Does it still gives 2 rows?

  • http://www.techmindz.com Deepak Mittal

    Did you try running the query directly through phpmyadmin? Does it still gives 2 rows?

  • Mark Skayff

    Nice one to get next auto_increment value.

  • Mark Skayff

    Nice one to get next auto_increment value.

Ubuntu 11.04

The next version of Ubuntu is coming soon

Follow me

Sponsors