如何在Codeigniter中基于特定值显示行数

时间:2019-05-21 10:32:21

标签: php mysql database codeigniter mysql-num-rows

我正在寻找一种使用Codeigniter根据特定列数据显示行数的解决方案。

这基本上是针对商店注册项目的。我有一个名为“ shopowner”的数据库表,其中有一个名为status的列。并且此状态列只有3个值。即。如果状态为0,则记录正在等待批准,批准后,状态将变为1和2,以被拒绝。现在,在我的仪表盘中,我需要显示未决,已批准和已拒绝记录的总数。谁能帮我这个忙,请告诉我在模型,控制器和视图中添加什么。我对Codeigniter完全陌生。预先感谢。

型号

public function count_rows($status)
    {
        $this->db->select('status, COUNT(status) as total');
        $this->db->group_by('status', $status);  
        $this->db->get('shopowner');
    }

预期的输出将类似于

总注册人数:4 待批准:2 已批准:1 拒绝:1

3 个答案:

答案 0 :(得分:0)

如果要在一个查询中获取所有统计信息,则可以使用以下代码

 $this->db->select('status, COUNT(status) as total');
 $this->db->group_by('status');  
 $this->db->get('shopowner');

但是,如果您想获得特殊的状态计数,则必须将您的状态代码添加到参数

$this->db->where(['status' => $status]);
$result = $this->db->get('shopowner');
echo $result->num_rows();

我希望这对您有帮助

private function count_rows($status) {
    $this->db->where(['status' => $status]);
    return $this->db->get('shopowner')->num_rows();
}

在您的控制器中

    $data = [
        'pending_approval' => $this->count_rows(4),
        'approved' => $this->count_rows(2),
        'rejected' => $this->count_rows(1)
    ];
    $this->load->view('your_view', $data);

您可以使用<?=$approved?>调用$ data项

答案 1 :(得分:0)

无需在代码的第一行给出“状态”列,只需使用“ $ this-> db-> select('COUNT(*)作为总数”);'在第一行,并使用带状态列的where子句,而不是在group_by子句中使用的“状态”列。您可以尝试以下代码吗?

public function count_rows($status)
{
    $this->db->select('COUNT(*) as total');
    $this->db->from('shopowner');
    $this->db->where('status', $status);
    $this->db->group_by('status');  
    $this->db->get();
}

答案 2 :(得分:0)

我创建了一个名为 shopowner 的数据库表,其中包含 4 个名为:idnamestatustype_name 的列。状态列只有 3 种类型的值,就像您描述的那样。如果状态为 0,则记录正在等待批准,一旦批准,状态将变为 1 和 2 表示拒绝。 type_name 显示拒绝已批准并在其中等待,type_name 具有拒绝已批准或等待等名称类型,id 是自动生成的,名称是客户名称。

模型

$this->db->select('type_name, COUNT(status) as star ');
$this->db->from('shopowner');
$this->db->group_by('status');

控制器

$data['user']=$this->your_model->name();
$this->load->view('your_view', $data);

查看

<table>
  <tr>
<th>name</th>
<th>total</th>
</tr>
    <?php foreach( $user as $users ){
        ?>
     <tr>
    <td><?php echo $users->type_name?></td>
    <td><?php echo $users->star?></td>
    </tr>
    <?php } ?>
  </table>