phpcodeigniteraveragequery-builder

Return the AVG() of a database table column from a model method using CodeIgniter's query builder


I need to calculate in a function the average score of a column named: "totalscore" from my database table "score". I tried to use the select_avg() query builder method, 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;
}

Solution

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