Page 1 of 1

max() not getting any value

Posted: Thu Apr 10, 2008 1:53 am
by eccen
id | name
------------------
1 | abc
2 | def
3 | ghi
4 | jkl

I have a table setup like above..
and I am trying to get the largest 'id' value with max()

Code: Select all

   $mysqldb->query("SELECT max(id) FROM TbName");
    $id = $mysqldb->fetchObject();
    $id = $id->value;
and... I am not getting anything for $id
functions used for the script:

Code: Select all

   function query($query) {
        try {
            $this->result = @mysql_query($query,$this->linkid);
            if (! $this->result)
                throw new Exception("The database query failed.");
        }
        catch (Exception $e) {
            echo ($e->getMessage());
        }
        $this->querycount++;
        return $this->result;
    }
 
    function fetchObject() {
        $row = @mysql_fetch_object($this->result);
        return $row;
    }
Can somebody give me a direction to this? I have been trying to figure it out for hours now :|

Re: max() not getting any value

Posted: Thu Apr 10, 2008 2:04 am
by Benjamin
You aren't specifying an alias so "id" is not being returned. Instead, "max(id)" is being returned. In order to return the value as id you would use the following query:

Code: Select all

 
SELECT max(id) AS id FROM TbName
 

Re: max() not getting any value

Posted: Thu Apr 10, 2008 2:33 am
by eccen
Just tried but still the same result :?

Re: max() not getting any value

Posted: Thu Apr 10, 2008 2:34 am
by Benjamin
Works for me. Maybe there is an error in the php code.

EDIT: Maybe try backticks around id?

Code: Select all

 
SELECT max(`id`) AS `id` FROM tablename;
 
Might want to post your actual query too.

Re: max() not getting any value

Posted: Thu Apr 10, 2008 2:48 am
by EverLearning
Properties in the object have the same names as fields in your sql statement, so if your field is `id`, your object property is also named id

Code: Select all

$mysqldb->query("SELECT max(id) as id FROM TbName");
$row = $mysqldb->fetchObject();
$id = $row->id;