如何计算和显示学生的平均分数?
这是我的数据库表 https://i.stack.imgur.com/edMKs.jpg
Primary_model
$average = mysql_query("SELECT AVG(tot_score) AS avgscore FROM scores_primary");
while($row = mysql_fetch_array($average)){
echo $row['avgscore'];
}
控制器
$this->load->view('student/view',$data);
视图
<span><b>AVERAGE RESULT:</b><?php echo $row['avgscore']; ?></span>
不显示平均分数。我做错了什么?
如果你想要平均,你没有以正确的方式做到这一点,你可以更好地在控制器中创建一个函数,如下所示
function calculateaverage(){
$query = $this->db->select('AVG(totalscore) as average_score')->from('score')->get();
return $query->row()->average_score;
}
然后你可以调用它
function index(){
$data['avg'] = $this->calculateaverage();
$this->load->view('your-page', $data);
}
然后你可以在你的页面中回显它
<span><b>AVERAGE RESULT:</b><?php echo $avg; ?></span>
如果您想要特定学生的平均值,则可以将student_id传递给函数
function calculateaverage($student_id){
$query = $this->db->select('AVG(totalscore) as average_score')->from('score')->where('student_id', $student_id)->get();
return $query->row()->average_score;
}
这就是对我有用的
学生控制器
// $query = $this->db->query('SELECT AVG(tot_score) FROM scores_primary WHERE student_id = ?');
$sql = "SELECT AVG(tot_score) as average_score FROM scores_primary WHERE student_id = ?";
$query = $this->db->query($sql, array($student['id']));
$data['average_score'] = $query->result()[0]->average_score;
视图
<span><b>AVERAGE RESULT:<?php echo $average_score; ?></b></span>