ubiquibacon ubiquibacon - 1 year ago 47
MySQL Question

MySQL MAX(id) called from PHP produces strange value

I am just trying to get the auto incremented value of a table that is currently the highest. I do not need to know what the next auto increment is, just the highest value of what is in the table right now. I am using the code below, but regardless of what the actual auto increment is, what table I last inserted into, what table was last updated / modified, or any other factors that I can see, the value always returns

Resource id #4
. This is perplexing to me for two reasons. First I don't understand why the number is always
, second I do not understand why I am getting back a string value (with letters and a symbol) instead of just an integer. What is the deal here?

<?php $highest_id = mysql_query("SELECT MAX(c_id) FROM customers"); ?>


mysql_query doesn't return the value from the query, it returns a result resource. To get the actual value, you need to use one of the mysql_fetch_* functions, passing it the result resource you got from mysql_query.

    $result = mysql_query("SELECT MAX(c_id) FROM customers");
    $row = mysql_fetch_row($result);
    $highest_id = $row[0];

or the shorter...

    $highest_id = mysql_result(mysql_query("SELECT MAX(c_id) FROM customers"), 0);