tags:

views:

35

answers:

3

Hi all, 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 4, 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"); ?>

+2  A: 

mysql_query returns a result handle, not the actual result. In other words, your query's result is saved as resource id #4 (and that's not guaranteed to be the same always, it's coincidence if you see it that way all the time).

To access the result you need to use something like mysql_fetch_array or one of the other functions in the same family.

Something like this:

<?php 

$query = mysql_query("SELECT MAX(c_id) as max FROM customers"); 
$row = mysql_fetch_array($query);
$highest_id = $row['max'];

?>
Mark E
+4  A: 

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.

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

or the shorter...

<?php
    $highest_id = mysql_result(mysql_query("SELECT MAX(c_id) FROM customers"), 0);
?>
Amber
I feel kind of stupid posting that up there, but yeah, I actually did have it like that at first, but the result returned was `''`. I'll edit my post to show you what I tried at the very first (which is what you are suggesting).
typoknig
Ok, i see what I did wrong now. My original code I used `mysql_fetch_array` and then i messed up where you have the `0` in `$row[0]`. Thanks for your help!
typoknig
A: 

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

Shoaib
Very concise, but should be:$highest_id = mysql_result(mysql_query("SELECT MAX(c_id) FROM customers"), 0);
TomWilsonFL