2013-12-14 87 views
0

我有这个表(演示):单查询,以检查结果

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个随机问题将被显示给用户,然后用户选择的答案。所以,当用户提交表单(答案)时,如何检查用户提交的是否正确?

我现在要做的是,通过在提交answersheet每个question_id循环,然后做一个查询来检查,如果答案是正确的这样的(伪码):

$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'; 

是否有可能做在单个查询中检查答案?如果是这样,那么最好这样做吗?

回答

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

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