使用
Codeigniter 3
,我想显示MySQL
数据库中表中的所有记录。我还想包括所选记录的数量。
例如;
Showing x number of records;
record 1
record 2
record 3
etc
目前我有以下(有效);
// select all records
public function selectRecords() {
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
return $query->result_array();
}
// count all records
public function countRecords() {
$this->db->select('count(*) as count');
$this->db->from('records');
$query = $this->db->get();
return $query->row();
}
我的问题是我是否需要两个单独的查询才能实现此目的(
select and count
)?
有没有更有效的方法来实现我想要的?
你可以做这样的事情:
public function selectRecords()
{
$query = $this->db->get('records');
if ($query->num_rows() > 0 )
{
$records = $query->result_array();
$data['count'] = count($records);
$data['all_records'] = $records;
return $data;
}
}
将其从控制器传递到视图:
$data = $this->model_name->selectRecords();
/*print_r($data) to see the output*/
$this->load->view('your_view',$data);
所见:
<?php echo $count .' number of records';?>
你只能做:
public function selectRecords() {
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
return $query->result_array();
}
和
$records = $this->selectRecords();
$count = count($records);
在第一个函数本身中,您可以使用
$query->num_rows()
函数 获取计数
public function selectRecords() {
$return = array();
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
$return['count'] = $query->num_rows();
$return['records'] = $query->result_array();
return $return;
}
试试这个 它将帮助您提供记录分页
public function selectRecords($params = array(), $count = false) {
$offset = isset($params['offset']) ? $params['offset'] : '';
$limit = isset($params['limit']) ? $params['limit'] : '';
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
if ($count) {
return $this->db->get()->num_rows();
}
if (empty($offset) && !empty($limit)) {
$this->db->limit($limit);
}
if (!empty($offset) && !empty($limit)) {
$this->db->limit($limit, $offset);
}
$result = $this->db->get()->result();
return $result;
}
您的模型方法只需将 2d 有效负载返回到控制器(不需要同时计算行数)。
public function getAll(): array
{
return $this->db->get('records')->result_array();
}
在您的控制器中,如果您需要在该级别,您只需调用
count()
即可。如果视图仅需要计数,则仅在视图中调用 count()
。