【问题标题】:Count and display result based on type in codeigniter根据codeigniter中的类型计数并显示结果
【发布时间】:2016-11-20 11:00:18
【问题描述】:

我有下表

|id|user_type|
|1|Customers|
|2|Suppliers|
|3|Customers|
|4|Suppliers|
|5|Suppliers|
|6|Employees|

我想统计客户、供应商、员工的总数

  • 客户 (2)
  • 供应商 (3)
  • 员工 (1)
  • 这是我的html

           <a href="#" class="customers list-group-item">
                <span class="badge badge-info">
                     2
                </span>
                Customers
           </a>
            <a href="#" class="employees list-group-item">
                <span class="badge badge-danger">
                    3               
               </span>
                Employees           
           </a>
            <a href="#" class="suppliers list-group-item">
                <span class="badge badge-success">
                    1               
                  </span>
                Suppliers           
           </a>
    

    我的查询代码如下所示

         <?php
                     $this->load->model("User_model");
                     $query = $this->db->query('SELECT user_type, COUNT(Customers) AS total FROM `users` GROUP BY user_type');
    
           if ($query->num_rows() > 0)
        foreach ($query->result() as $row) 
            $data['users'] = array(
                'total' => $row->total,
            );
    
    echo $data['users'];
    

    此代码不起作用。感谢您的宝贵时间。

    【问题讨论】:

    • $data['users'] 在每次迭代中都会被覆盖。

    标签: php mysql codeigniter mysqli


    【解决方案1】:

    您的$data['users'] 变量在foreach 的每次迭代中都会被覆盖。 您需要做的 - 是 添加新项目$data['users']。使用[] 执行添加到数组:

    foreach ($query->result() as $row) {
        $data['users'][] = array(
            'type_name' => $row->user_type,
            'total' => $row->total,
        );
    }
    
    // `echo` will no work with `arrays`, use `print_r` instead
    print_r($data['users']);
    

    【讨论】:

    • 先生,我收到一个错误A Database Error Occurred Error Number: 1054 Unknown column 'Customers' in 'field list' SELECT user_type, COUNT(Customers) AS jobcount FROM users GROUP BY user_type跨度>
    • 你的栏目名称是user_type所以是COUNT(user_type) as total,请注意。
    • 我不想统计 user_type 但想统计客户、供应商和员工列
    • 请使用COUNT(user_type) as total 运行您的查询并查看结果
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 2019-09-22
    • 2011-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多