2013-12-14 85 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