Mugen Mugen - 2 months ago 7
PHP Question

how to echo variables into js objects dynamically

Trying to make a Question and answer with choices on a webpage which would retrieve question data from the database.
The var for the js object looks like this:



var questions = [{
question: "What is 2*5?",
choices: [2, 5, 10, 15, 20],
correctAnswer: 2
},...





Although I can make these have a fixed number of questions only, I would like to make it more dynamic.

This is what I have currently written:



<script type="text/javascript">
var questions = [
<?php
include "functions/connect.php";
$selqq="select * from quiz_question where QUIZ_ID=2";
$runqq=mysqli_query($con,$selqq);
while($rowqq=$runqq->fetch_array())
{
echo "{ question: '".$rowqq['QUESTION']."',
choices: [".$rowqq['CHOICE0'].",".$rowqq['CHOICE1'].",".$rowqq['CHOICE2'].",".$rowqq['CHOICE3']."],
correctAnswer: ".$rowqq['ANSWER']."},";
}
?>];
</script>





This does not work for me, maybe because of that "," near the end, and placing it at the beginning will do the same.
How do I make it so that I can place as many objects as I want in an array? is it possible?

Answer

change your script code like this

<script type="text/javascript">
        var questions =
        <?php
         $data = null;
         $i = 0;
        include "functions/connect.php";
        $selqq="select * from quiz_question where QUIZ_ID=2";
        $runqq=mysqli_query($con,$selqq);
        while($rowqq=$runqq->fetch_array())
        {    
            $data[$i]['question']  = $rowqq['QUESTION'];
            $data[$i]['choices']  = $rowqq['CHOICE0'].$rowqq['CHOICE1'].$rowqq['CHOICE2'].$rowqq['CHOICE3'];
            $data[$i]['correctAnswer'] = $rowqq['ANSWER'];
          $i++;
        }
         echo json_encode($data);
        ?>
   </script>