问题描述
function examResult($student_id,$exam_id){
global $conn;
$stmt = $conn->prepare("SELECT SUM(CASE WHEN answers.answered_option=questions.correct_option THEN questions.marks ELSE 0 END) AS obtain,exams.exam_name,exams.total_marks,exams.pass_marks FROM exams INNER JOIN questions ON exams.id=questions.exam_id INNER JOIN answers ON answers.question_id=questions.id WHERE answers.student_id = ? AND exams.id = ? ");
if($stmt){
return 'ok';
$stmt->bind_param('ii',$student_id,$exam_id);
$stmt->execute();
$result = $stmt->get_result();
if($result){
$row = $result->fetch_assoc();
return $row;
}
} else{
return false;
}
}
我期望上面的函数“确定”,但是它返回false。这意味着$ stmt没有执行。另外,我的两个参数$ student_id和$ exam_id都很好。
SELECT SUM(CASE WHEN answers.answered_option=questions.correct_option THEN questions.marks ELSE 0 END) AS obtain,exams.pass_marks FROM exams INNER JOIN questions ON exams.id=questions.exam_id INNER JOIN answers ON answers.question_id=questions.id WHERE answers.student_id = 18 AND exams.id = 24
解决方法
通过在末尾添加GROUP BY语句来解决它。
$stmt = $conn->prepare("SELECT SUM(CASE WHEN answers.answered_option=questions.correct_option THEN questions.marks ELSE 0 END) AS obtain,exams.exam_name,exams.total_marks,exams.pass_marks FROM exams INNER JOIN questions ON exams.id=questions.exam_id INNER JOIN answers ON answers.question_id=questions.id WHERE answers.student_id = ? AND exams.id = ? GROUP BY exams.id");