单个查询来检查结果

时间:2013-12-14 08:02:22

标签: php mysql sql

我有这张桌子(演示):

questions
----------
question_id | question       | choice1 | choice2 | choice3 | choice3 | choice4 | answer
---------------------------------------------------------------------------------------
1           | what is..      | apple   | orange  | grapes  | pinea   | blah    | 2
2           | what is..      | apple   | orange  | grapes  | pinea   | blah    | 4
3           | what is..      | apple   | orange  | grapes  | pinea   | blah    | 1
4           | what is..      | apple   | orange  | grapes  | pinea   | blah    | 2
5           | what is..      | apple   | orange  | grapes  | pinea   | blah    | 3
6           | what is..      | apple   | orange  | grapes  | pinea   | blah    | 4

将向用户显示一组5个随机问题,然后用户选择答案。因此,当用户提交表单(答题表)时,如何检查question_id&用户提交的answer是否正确?

我现在所做的是,遍历提交的答案表中的每个question_id,然后执行查询以检查答案是否正确( psuedocode ):

$wrong_questions = $total_questions_in_answersheet;
foreach($question in $answersheet)
{
   $c = SELECT COUNT(*) FROM `questions` WHERE `question_id` = $question_id AND `answer` = $answer;

   if($c > 0)
     $wrong_questions--;
}

if($wrong_questions > 0)
  echo 'FAILED';
else
  echo 'WELL DONE';

是否可以在单个查询中检查答案?如果是这样,以这种方式做得更好吗?

2 个答案:

答案 0 :(得分:1)

$where = implode(' OR ', array_map(function($question) {
    return "(question_id = $question[question_id] AND answer != $question[answer])";
}, $answersheet));

$sql = "SELECT COUNT(*) AS wrong_questions FROM questions WHERE $where";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
if ($row['wrong_questions'] > 0) {
    echo 'FAILED';
} else {
    echo 'WELL DONE';
}

答案 1 :(得分:0)

循环中运行查询通常被认为是一种不好的做法;所以,事实上,我只会做两件事: 首先,SELECT在关联数组中与id相关联的所有正确答案,如$answers['id']['answer']; 其次,通过$answers将提交的答案与id数组进行比较。