1
\$\begingroup\$

I am creating a multiple choice quiz game with PHP and Javascript. Questions can have 2 to 6 answers. I have been using the PHP queries in the code below to get arrays of the questions of a quiz, and the answers for each questions.

I now want to use this data in Javascript, and want to make it so each time a user clicks next question, a question and corresponding answers are displayed.

I think (but am not sure) that the best way to do this is to combine the arrays into one where the question array contains the answers arrays before converting to a javascript array.

Is this really the way I should do this, and if so how do I do so?

$thisquizid = $_POST['quizidvalue'];
    for ($j = 0; $j < $questionrows; ++$j)
        {
            $questionresult = pg_fetch_array($questionquery); 
            $answerquery = pg_query($db_handle, "SELECT * FROM answer WHERE questionid = '$questionresult[0]'");
            $answerrows = pg_num_rows($answerquery);  

        for ($i = 0; $i < $answerrows; ++$i)
            {
                $answerresult = pg_fetch_array($answerquery); 
            }

    }
\$\endgroup\$
2
  • 1
    \$\begingroup\$ JSON - JavaScript Object Notation, is a better way to pass information to/from PHP and JS. PHP has built in functions to encode and decode to JSON. php.net/manual/en/book.json.php \$\endgroup\$
    – MECU
    Commented Mar 16, 2013 at 23:58
  • \$\begingroup\$ Javascript is perfectly capable of coping with arrays that themselves contain arrays. Your problem is simply how to transfer a data structure between PHP and Javascript. JSON should serve nicely, it's easily encoded and decoded in both JS and PHP and can export complicated structure. Failing that, there's XML. \$\endgroup\$
    – GordonM
    Commented Mar 17, 2013 at 13:21

1 Answer 1

1
\$\begingroup\$

Running a SQL statement in a loop is in general a bad idea. Depending on your $questionsrow you might send a lot of not needed requests.

In relation to MECUs hint you could use something like:

$questions=array();
//add constrains to select only some questions or sort the answers
$result=...query($db_handle, "SELECT * FROM answer");
while ($row=...fetch_array($result))
{
    $qid=$row['questionid'];
    if (!isset($questions[$qid])) =array(); //create subarray if new question
    $questions[$qid][]=$row //append a new element to the question array
}
$json=json_encode($questions);

I.e. $questions[1] will contain a array with all your answers to question 1. The sorting of the answers can be moved to SQL query, also if you don't need all fields you can restrict this in the SQL and don't need to take care of this in your PHP.

\$\endgroup\$
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.