I'm trying to display an average result from the database to the view but I keep getting this error:
A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Filename: views/resultview.php
Line Number: 38
Here is the code from the Controller:
$average['avg'] = $this->quiz->getAverage($quizid);
$this->load->view('resultview',array('quiz' => $quiz,
'score' => $score,
'average_score' => $average));
The function from the model is the following:
function getAverage($quiz)
{
//get percentage from the database
$this->db->select_avg('score');
$this->db->where('id', $quiz);
$res = $this->db->get('userScoreQuiz');
if ($res->num_rows() != 1) {
// there should only be one row - anything else is an error
return false;
}
return $res->result_array();
}
and the code from the view it is:
<h4> Avg. score on all previous attempts: <?php echo $average_score['avg'] ?> %</h4>
I can't seam to find out why it does this.
Thank you for your help guys.
function getAverage($quiz)
{
//get percentage from the database
$this->db->select_avg('score');
$this->db->where('id', $quiz);
$res = $this->db->get('userScoreQuiz');
if ($res->num_rows() != 1) {
// there should only be one row - anything else is an error
return false;
}
return $res->row()->score;
}
from docs :
$this->db->select_avg('age');
$query = $this->db->get('members'); // Produces: SELECT AVG(age) as age FROM members
That's too much of coding you got going on, Here is an Elegant solution:
function getAverage($quiz)
{
//get percentage from the database
$query = $this->db->select('AVG(score) as average_score')->from('userScoreQuiz')->where('id', $quiz)->get();
return $query->row()->average_score;
}
For your view
$data['quiz'] = //fill this area
$data['average_score'] = $this->quiz->getAverage($quizid);
$data['score'] = //fill this area
$this->load->view('resultview', $data);
And they will be accessable as $quiz, $average_score, $score
replace the
echo $average_score['avg'];
to
print_r($average_score['avg'];
because that not one variable, that is set of array
codeigniter result_array() returns data as array. And array index starts with 0 index.
"$average_score['avg']" this should be undefined index. Try to access result array as $average_score['avg'][0]['score'] if you don't want to change in your function.
if you want to avoid extra array index then return results using row() instead on result_array().
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.