Codeigniter 选择并统计 MySQL 记录

问题描述 投票:0回答:5

使用

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
)?

有没有更有效的方法来实现我想要的?

php codeigniter codeigniter-3
5个回答
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
投票

你只能做:

public function selectRecords() {
    $this->db->select('*');
    $this->db->from('records');
    $query = $this->db->get();
    return $query->result_array();
}

$records = $this->selectRecords();
$count = count($records);

1
投票

在第一个函数本身中,您可以使用

$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;
} 

1
投票

试试这个 它将帮助您提供记录分页

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;
}

0
投票

您的模型方法只需将 2d 有效负载返回到控制器(不需要同时计算行数)。

public function getAll(): array
{
    return $this->db->get('records')->result_array();
}

在您的控制器中,如果您需要在该级别,您只需调用

count()
即可。如果视图仅需要计数,则仅在视图中调用
count()

© www.soinside.com 2019 - 2024. All rights reserved.