CodeIgniter Forums
How do I get the last 3 records in a table? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: How do I get the last 3 records in a table? (/showthread.php?tid=8824)



How do I get the last 3 records in a table? - El Forum - 06-02-2008

[eluser]symonel[/eluser]
Hi all

Any idea how I could get the last 3 records in a table? I'm trying to get the last one with this:
Code:
$this->db->select_max('product_id')
but I need to use several fields from the table in the view, and the problem is the query only returns the product_id.
Code:
function get_last_products ()
    {
        $this->db->select_max('product_id');
        $this->db->from('products');
        
        $query = $this->db->get();
        return $query;
    }
So when I try to display something like this in the view:
Code:
<?php foreach($last_products->result() as $row): ?>
<?=$row->product_name?>
<?php endforeach; ?>
I get the following error:
Quote:Message: Undefined property: stdClass::$product_name
What I would actually like is something like
Code:
SELECT TOP 3 FROM products ORDER BY product_id DESC
but I have no idea how to write it in Code igniter.
Please help!


How do I get the last 3 records in a table? - El Forum - 06-02-2008

[eluser]alekz[/eluser]
Try This!!

Code:
SELECT * FROM products ORDER BY product_id DESC LIMIT 3

Limit gives you the first three rows

i hope this can help you....


How do I get the last 3 records in a table? - El Forum - 06-02-2008

[eluser]symonel[/eluser]
Yes! Thanks, it worked.