使用Codeigniter 3仅显示数据库中的最后5条记录
问题描述:
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
答
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());
答
public function get_comments ($id) {
$this->db->select('*');
$this->db->order_by('id', 'DESC');
$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();
}
答
Try this
public function get_comments ($id) {
$sql = 'SELECT * FROM (SELECT Item_comments.id i_id,Item_comments.column_name1,Item_comments.column_name2 FROM Item_comments WHERE Item_comments.checklist_item_id = ' . $id . ' AND Item_comments.status = 1 ORDER BY Item_comments.id DESC LIMIT 5) T1 ORDER BY i_id ASC';
$query = $this->db->query($sql);
return $query->result_array();
}
答
Try this
function get_comments($start,$limit,$id)
{
$condition = array('checklist_item_id' => $id,'status'=>1);
$this->db->order_by('id', 'DESC');
$this->db->limit($limit, $start);
$query = $this->db->get_where('Item_comments',$condition);
$rows = $query->result();
return $rows;
}
答
Try this one :
public function get_comments ($id) {
$this->db->select('*');
$this->db->order_by('id', 'DESC');
$this->db->from('Item_comments');
$this->db->limit('0,5');
$this->db->where(array('checklist_item_id' => $id, 'status' => 1));
$query = $this->db->get();
return $query->result_array();
}