views:

167

answers:

3

I need the very last valid entry in a database table which would be the row with the greatest primary key. So using mysqli, my query is "SELECT MAX(id) FROM table LIMIT 1". This query returns the correct number(using print_r()) but I cannot figure out how to access it. Here is the main code. Note that the $this->link refers to class with a mysqli connection.

$q="select max(id) from stones limit 1";
    $qed=$this->link->query($q) or die(mysqli_error());
    if($qed){
        $row=$qed->fetch_object();
        print_r($row);
        echo $lastid=$row;//here is the problem
    }

The valid line print_r($row) echos out "stdClass Object ( [max(id)] => 68 )"

+1  A: 

I need the very last valid entry in a database table which would be the row with the greatest primary key.

You say you want the last entry but you're only fetching the ID. Presumably you intend to use this to fetch the entire row with a second query.

Instead you could do the whole operation in one query:

SELECT *
FROM stones
ORDER BY id DESC
LIMIT 1
Mark Byers
Thanks for the reply but I only want the id
Theopile
+1  A: 

Have you tried :

$row->max(id)? or $lastid=$row["max(id)"];

You may need to do a select max(id) as "MaxID" and $lastid=$row->MaxID;

Gary
$row->max(id) gives an error
Theopile
+3  A: 

You need to name the aggregate result.

SELECT MAX(id) AS maxid FROM stones

Then you can access the value like $row->maxid.

nikc
Thanks that works. I found a less cleaner solution and that is by using fetch_array() instead of fetch_object. But, I will try yours.
Theopile