claudios claudios - 6 months ago 35
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

Model

public function get_comments ($id) {
$this->db->select('*');
$this->db->order_by('id', 'ASC');
$this->db->from('Item_comments');
$this->db->limit('5');
$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

Answer

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());