php codeigniter计数行

Nil*_*lab 11 php codeigniter

我是codeigniter的新手,我想计算数据库表中的所有行,但查询不能检索确切的行总数.这是模型

public function countRow(){
$query = $this->db->query("SELECT *,count(id) AS num_of_time FROM home");
    // print_r($query->result());
    return $query->result();
}
Run Code Online (Sandbox Code Playgroud)

这是控制器

public function countTotalrow(){
     $data['query'] = $this->home_model->countRow(); 
}
Run Code Online (Sandbox Code Playgroud)

这是观点

foreach ($num_of_time as $row){
    <span><?php print_r($row->id);?></span>
Run Code Online (Sandbox Code Playgroud)

mar*_*osh 31

您可以使用辅助函数 $query->num_rows()

它返回查询返回的行数.你可以像这样使用:

$query = $this->db->query('SELECT * FROM my_table');
echo $query->num_rows();
Run Code Online (Sandbox Code Playgroud)

  • 当数据库引擎只能从其元数据存储中返回总行数时,没有理由运行完整查询.这是资源浪费,不会很好地扩展.不要查询整个表,而是使用`$ this-> db-> count_all_results()` (7认同)

小智 11

使用此代码:

$this->db->where(['id'=>2])->from("table name")->count_all_results();

要么

$this->db->from("table name")->count_all_results();


小智 5

你可以试试这个

    $this->db->where('field1',$filed1);
    $this->db->where('filed2',$filed2);
    $result = $this->db->get('table_name')->num_rows();
Run Code Online (Sandbox Code Playgroud)