claudios claudios - 10 months ago 71
PHP Question

Display only last 5 records from database using Codeigniter 3

I wanted to get recent records from database limit only to 5. I used the code below but not working. Maybe I missed something or the whole query is wrong. Please guide me. Thanks


public function get_comments ($id) {
$this->db->order_by('id', 'ASC');
$this->db->where(array('checklist_item_id' => $id, 'status' => 1));

$query = $this->db->get();
return $query->result_array();

Note: query works fine and get 5 records from db but I want to
position the recent into the bottom. Thanks


To get the last results you need to order them descending

$this->db->order_by("id", "desc");

Of course you can also use other columns instead of id.

To order your results ascending:

$this->db->order_by("id", "asc");

To reverse the resulting array:

$results = get_comments();
$results = array_reverse($results);

Or if you would like to do it in the function:

return array_reverse($query->result_array());