CodeIgniter:从表

时间:2019-04-30 05:19:05

标签: sql codeigniter codeigniter-3

我有一个包含个人数据的表,例如姓名,性别,地址等。我的问题是,如何从表中获得男女总数?

这是我的SQL查询:

SELECT gender, COUNT(*) AS total
FROM personaldata
GROUP BY gender

到目前为止,这是我在模型中的代码:

public function gender_count()
{
    $this->db->select('gender, count(*) as total');
    $this->db->from('personaldata');
    $this->db->group_by('gender');

    $query = $this->db->get()->row()->total;
    return $query->result();
}

那么,如何将该SQL查询写入CI模型和控制器?我只想显示我网站上的性别总数。

谢谢

3 个答案:

答案 0 :(得分:1)

  

有两种方法可以做到,您可以选择一种感到轻松

型号:

public function gender_count()
{
    $response = array();
//for female
    $this->db->select('count(id) as ftotal');//id should be primary key
    $this->db->from('personaldata');
    $this->db->where('gender','f');
    $this->db->group_by('gender');
    $query = $this->db->get();
    if ($query->num_rows() > 0) {
        $response['f'] = $query->row('ftotal');
    }else{
        $response['f'] = 0;
    }
//for male
    $this->db->select('count(id) as mtotal');//id should be primary key
    $this->db->from('personaldata');
    $this->db->where('gender','m');
    $this->db->group_by('gender');
    $query = $this->db->get();
    if ($query->num_rows() > 0) {
        $response['m'] = $query->row('mtotal');
    }else{
        $response['m'] = 0;
    }
    return $response;//assosiative array
}

OR

public function gender_count()
{
    $response = array();
    $this->db->select('gender,count(id) as total');//id should be primary key
    $this->db->from('personaldata');
    $this->db->group_by('gender');
    $query = $this->db->get();
    if ($query->num_rows() > 0) {
        foreach($query->result() as $row){
          $response[$row->gender] = $row->total;
        }
    }else{
        $response['f'] = 0;
        $response['m'] = 0;
    }
    return $response;//assosiative array
}

控制器:

$data = array();
$genderCount = $this->Gender_model->gender_count();
$data['fcount'] = $genderCount['f'];
$data['mcount'] = $genderCount['m'];
$this->load->view('genderCount',$data);

查看:

<span>Female:</span><b><?php echo $fcount;?></b>
<span>Male:</span><b><?php echo $mcount;?></b>

答案 1 :(得分:0)

您可以通过Count(*)获得性别总值,并从@OutputValue发送该值

Declare  @OutputValue int
select @OutputValue=COUNT(*) from personaldata

答案 2 :(得分:0)

您可以在模型中使用以下函数,然后从控制器调用它。

  

型号

description=foo&price=123...
  

控制器

{
    "description": "foo",
    "price": 123,
    ...
}

注意::我以模型名称和表名称为例,因此您需要使用模型名称和表名称。

我希望这对您有用。