Welcome Guest, Not a member yet? Register   Sign In
How do I get the last 3 records in a table?
#1

[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!
#2

[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....
#3

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




Theme © iAndrew 2016 - Forum software by © MyBB