如何将此sql代码转换为Codeigniter ActiveRecord

时间:2012-10-18 11:17:29

标签: sql codeigniter activerecord

我在表PRVO中有一行有四种类型的值:第一,第二,第三,第四

我想要算出第一次出现多少次以及第二次出现多少次以及第三次出现多少次以及第四次出现多少次并且如此回应:

First = 4
Second = 5
.....

我有以下代码:

$anketadb->select('prvo');
$anketadb->from('anketadata');
$anketadb->group_by('prvo');

如何添加计数以获得我上面写的结果? 提前致谢

更新:

现在我有情况: MODEL:

$anketadb = $this->load->database('anketa',TRUE);

    $anketadb->select('prvo');
    $anketadb->from('anketadata');
    $anketadb->group_by('prvo');
$result =   $anketadb->get();

$result =   $result->result_array();

$count  =   array('povremeno' => 0, 'nikad' => 0, 'svakibroj' => 0, 'prodajemkupujem' => 0);

foreach($result as $row){
    switch($row){
        case 'povremeno' :  $count['povremeno']++; break;
        case 'nikad' : $count['nikad']++; break;
        case 'svakibroj' :  $count['svakibroj']++; break;
        case 'prodajemkupujem' : $count['prodajemkupujem']++; break;
    }
}
return $count;

控制器:

$this->load->model('anketerezultati_model');
    $data['count'] = $this->anketerezultati_model->prvo();
    $this->load->view('ankete/rezultatiankete', $data);

查看:

echo "povremeno".$count['povremeno'];
echo "nikad".$count['nikad'];

两个结果都是0 ......我找不到错误。

2 个答案:

答案 0 :(得分:0)

希望你需要这个:

$this->db->select('*');
$this->db->from('anketadata');
$this->db->group_by('prvo');
$result =   $this->db->get();

//Result set
$result =   $result->result_array();

<强>更新

$count  =   array('first' => 0, 'second' => 0, 'third' => 0, 'fourth' => 0);

foreach($result as $row){

    switch($row['<fieldName>']){

        case 'first' :  $count['first']++; break;
        case 'second' : $count['second']++; break;
        case 'third' :  $count['third']++; break;
        case 'fourth' : $count['fourth']++; break;
    }
}

最后你在$count数组中出现了first.second ....要将出现次数$count['first']用于第二个$count['second '] .....

答案 1 :(得分:0)

修改

$this->db->select('prvo');
$this->db->from('anketadata');
$this->db->group_by('prvo');
$query = $this->db->count_all_results();

return $query;