【问题标题】:Why doesn't CI convert count statement to an array?为什么 CI 不将 count 语句转换为数组?
【发布时间】:2019-06-16 21:41:44
【问题描述】:

我正在努力让您可以在我的网站上查看某些内容的行数,我将结果转换为数组,然后在视图中对其进行 foreach,但它调用参数无效。

正如我所说,我尝试了通常的做法,将数据从模型传递到控制器,然后再传递到视图。我尝试将$query->num_rows();count_all_results 返回到控制器数组以便在视图中使用,两者均无效。

controller.php

  $this->load->model('Main');
  $data = array(
    'getapps' => $this->Main->countapps()
  );
  $this->load->view('header', $data);

view.php

<?php foreach($getapps as $apps) {
?>

<a href="http://localhost/Dir/index.php/Controller/Apps" class="a-m" id="a-m-id">apps <strong><?php echo $apps; ?></strong></a>

<?php }
?>

model.php

public function countapps() {

$this->db->where('usedby', $_SESSION['uid']);
$this->db->get_where('apps', 'appstatus', 'Used');
$stmt = $this->db->count_all_results();

  return $stmt;
}

我希望视图显示行数,而不是告诉我 foreach 参数的提供无效。

【问题讨论】:

    标签: php codeigniter count


    【解决方案1】:

    在 CI 中,$this-&gt;db-&gt;count_all_results() 替换数据库查询中的 $this-&gt;db-&gt;get()。所以你不能同时使用$this-&gt;db-&gt;get_where()$this-&gt;db-&gt;count_all_results(),而是使用num_rows()

    像这样编写你的模型函数:

    public function countapps() {
    
     $query=$this->db->where('usedby', $_SESSION['uid'])
                     ->get_where('apps', 'appstatus', 'Used');
      $stmt = $query->num_rows();
    
      return $stmt;
    }
    

    您可以将控制器更改为更短:

    $data['getapps'] => $this->Main->countapps();
    

    那么在您看来,您不需要使用foreach(),因为 $data['getapps'] 不是数组而是数字。您可以像

    一样在视图中输出它
    echo $getapps;
    

    【讨论】:

    • 它会抛出这个错误:Call to undefined method CI_DB_mysqli_driver::num_rows()
    • 是的,我补充了,现在错误是Call to a member function num_rows() on array
    • @frogman578 抱歉搞混了,现在是正确的,要使用num_rows(),你需要先有一个查询结果...
    • 我一开始就是这样,无效的foreach 参数
    猜你喜欢
    • 2012-05-22
    • 1970-01-01
    • 2014-03-01
    • 2019-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多