Code igniter database calculate column average

随声附和 提交于 2019-12-02 15:03:15

问题


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:


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;
}


来源:https://stackoverflow.com/questions/34598633/code-igniter-database-calculate-column-average

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!