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