Maximum value in field "id"

I am trying to get the maximum value in field “id”.

What is really happening is that “$id” is actually taking the lowest value of the “$rowid” array.

How do I get the highest value in “$rowid”?

    $sql = "SELECT `id` FROM `table1`";
    $result = mysql_query($sql, $conn);
    $rowid = mysql_fetch_array($result, MYSQL_ASSOC);
    if ($rowid != "") {
    	$id  = max($rowid);

P.S. You can not take the “max” of a null array.

is id auto-increment?

order by id desc limit 1

SELECT MAX(id) AS max_id FROM table1

there is no need to retrieve the entire table just to find the largest value

id is Auto_Increment. Could you please elaborate?

Spot on, though that still has to count through the order tree. This is functionally identical:


… and may run faster despite the more complex query since it will use the existing index. I think that’s what Litebearer was suggesting.

Unless of course need that exact query because you’re showing all of those results AND need to know the last ID… if you were using mysqli instead of mysql commands, you could seek to the last result, pull it’s id, then seek to start rather than run a separate query. in PDO you could fetchAll letting you process it as a normal array (the last() command would be handy then) – just be sure in that case to release the statement object so it’s not hogging memory.