开发者

How to compare array with database in php

if you folks can help me out with this problem. im trying to build a questionere with php.

table:

id_quiz   question    answer
82         开发者_Go百科q1            1 
83         q2            4 
84         q3            1
85         q4            4 

ive got two arrays;

1. $all_ids = [82,83,84,85]

2. $all_answers = [1,4,1,4] -> if the answer is correct then count them.

my question is how do compare those two array with database?

  1. '$all_ids' is the id for database table.
  2. '$all_answers' is the answers.

$all_ids[82] == ($all_answer[1] -> compare answer with database for id 82)

$all_ids[83] == ($all_answer[4] -> compare answer with database for id 83)

$all_ids[84] == ($all_answer[1] -> compare answer with database for id 84)

my current code seem not working:

$total_correct = 0;

foreach ($all_ids as $ids){

    $check = $db->query("SELECT * FROM quiz WHERE id_quiz='$ids' ");
    $row = $check->fetch_assoc();

    foreach($all_answers as $answers) {

        if($row['answer'] == $answers) {
            $total_correct++;   
        }       

    }
}

i hope my question makes any sense :)


Change your two answers arrays into one like this:

$answers[82] = 1
$answers[83] = 4

foreach($answers as $id => $ans)
{
$sql = "select * from quiz where id_quiz = $id"
db->query($sql)
$row = $check->fetch_assoc();
if($row['answer'] == $ans)
{
  totalcorrect++
}

}

Thats a quick answer, not sure if you need more detail?


Use php's implode function to glue the ID's together: implode(",", $all_ids); Then u can use that to create one DB query (as cularis said) and iterate through those results to check (like matt said)

more info:

  • http://www.w3schools.com/sql/sql_in.asp
  • http://php.net/manual/en/function.implode.php
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜