使用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
)吗?
有没有更有效的方法来实现我想要的?
答案 0 :(得分:1)
您可以这样做:
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';?>
答案 1 :(得分:0)
你只能做:
public function selectRecords() {
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
return $query->result_array();
}
和
$records = $this->selectRecords();
$count = count($records);
答案 2 :(得分:0)
在第一个函数中,您可以使用$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;
}
答案 3 :(得分:0)
试试这个 它将帮助您为记录提供分页
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;
}