Code igniter database calculate column average

2019-03-05 12:59发布

I need to calculate in a function the average score of a column named: "totalscore" from my database table "score" I tried to do Active record select_avg() but I am not getting anything. Any idea how I can do this?

function calculateaverage(){
        $dataArr = array();
        $data = $this->db->get('score');
        $maxrows = $data->num_rows();

        $data = $this->db->get('score');
        for ($i = 1; $i<= $maxrows-1; $i++){
            $this->db->select('totalscore');
            foreach ($data->result() as $row) {

            $dataArr[$i] = $row->totalscore;
            }
        }
        return $dataArr;

    }

1条回答
家丑人穷心不美
2楼-- · 2019-03-05 13:27

You can try this code, very simple and straight forward. write it in your model. use in Controller like $this->yourmodel->calculateaverage; basically we are telling codeigniter query builder to select the AVG of our totalscore..

function calculateaverage(){
$query = $this->db->select('AVG(totalscore) as average_score')->from('score')->get();
return $query->row()->average_score;
}
查看更多
登录 后发表回答