我正在构建一个搜索函数,我确信正确的方法是只获取您想要显示的结果数,在我的情况下是每页20个。我想知道对我来说,更改select('*')
语句以返回结果总数的最佳方法是什么——选择('count(*)');
并重新运行完全相同的查询?
$this->db->select('*');
$this->db->from('MyTable');
$this->db->where('some complex conditions');
$this->db->join('a bunch of joins);
$this->db->limit('20','$page*20');
至
$this->db->select('count(*)');
/* reuse this part */
$this->db->from('MyTable');
$this->db->where('some complex conditions');
$this->db->join('a bunch of joins);
/* reuse this part */
运行第一个查询
$q1 = $this->db->get()->result_array();
运行第二个查询
$q2 = $this->db->get('q1 with different select')->result_array();
array_merge($q1,$q2);
Codeigniter实际上有一个非常有用的分页助手:https://ellislab.com/codeIgniter/user-guide/libraries/pagination.html
如果你不喜欢使用它,你可以通过url将你所在的当前查询号传递给控制器
例如www.example.com/page/search/40。查询将使用该数字作为限制
你也可以这样做
// For required output
$this->db->select('');
$this->db->from();
$this->db->join();
$this->db->order_by();
$this->db->limit((int)$page['limit'],(int)$page['start']);
$list['list'] = $result->result();
// To count total number of rows
$this->db->select('');
$this->db->from();
$this->db->join();
$this->db->order_by();
$result_total = $this->db->get();
$list['list'] = $result->result();
$list['total'] = $result_total->num_rows();
return $list;
}