View Full Version : Finding out the highest number in an auto-incrementing table

01-21-2012, 11:24 AM
I have a row in a MySQL table called id, which auto-increments.

I was wondering if anyone knows a PHP solution to find out what the highest number in the row is?

I am thinking perhaps execute a MySQL query that will list the highest number, and then echo the result, like $row[id] in PHP?

01-21-2012, 01:06 PM
* Define $server, $username, $password, $database and $table here as follows:
* $server = name of mysql server.
* $username = username for mysql account.
* $password = password for mysql account.
* $database = name of database to use.
* $table = name of table containing the id column.

$conn = mysql_connect($server, $username, $password);
mysql_query("use $database;"):
$res = mysql_query("select max(id) from $table;");
$data = mysql_fetch_array($res);
$count = $data[0];

echo $count.PHP_ENDL;

Of course, you'll need to put some error checking in, but what I've posted above is the basic code to do what you want.

01-21-2012, 01:23 PM
Let me ask, what's your ultimate goal? It looks like you are after a wrong path.

01-21-2012, 02:15 PM
You can also use:

select id from <table> order by id desc limit 1

01-21-2012, 11:47 PM
Do you want the highest number there or do you want the one your script just inserted?

If the latter then you want "SELECT LAST_INSERT_ID()"

That function retrieves the last value actually inserted by the currently running copy of the script and will ignore any higher numbers inserted by someone else since you inserted yours.