max() not getting any value

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
eccen
Forum Newbie
Posts: 6
Joined: Fri Mar 28, 2008 12:41 am

max() not getting any value

Post 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 :|
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: max() not getting any value

Post 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
 
eccen
Forum Newbie
Posts: 6
Joined: Fri Mar 28, 2008 12:41 am

Re: max() not getting any value

Post by eccen »

Just tried but still the same result :?
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: max() not getting any value

Post 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.
User avatar
EverLearning
Forum Contributor
Posts: 282
Joined: Sat Feb 23, 2008 3:49 am
Location: Niš, Serbia

Re: max() not getting any value

Post 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;
Post Reply