user1925371
user1925371

Reputation: 33

Get last 5 of rows in database and sort by ASC

How can I get the last 5 of the rows in the database and sort it ascending? This is my code:

$this->query("
    SELECT  `chat`.`message`,
            `users`.`username`,
            `users`.`user_id`
    FROM    `chat`
    JOIN    `users`
    ON      `chat`.`user_id` = `users`.`user_id`
    ORDER BY `chat`.`timestamp`
    DESC
    LIMIT 5
");

Upvotes: 0

Views: 1015

Answers (3)

mallix
mallix

Reputation: 1429

If you are using CodeIgniter Active Record, then change:

$this->query

to

$this->db->query

Upvotes: 0

AbdElrhman
AbdElrhman

Reputation: 52

I think this is codeigniter, so retrieve data in array and loop backward. else modifying your query to select ascending

Upvotes: 0

Randy
Randy

Reputation: 16677

select * from (
    SELECT  `chat`.`message`,
            `users`.`username`,
            `users`.`user_id`,
            `chat`.`timestamp`
    FROM    `chat`
    JOIN    `users`
    ON      `chat`.`user_id` = `users`.`user_id`
    ORDER BY `chat`.`timestamp`
    DESC
    LIMIT 5
) 
order by timestamp asc

Upvotes: 3

Related Questions