0

I made a PHP quizzer. I have 2 tables in a database 'php quizzer' and 'quizzes'. The first one has 3 rows and is used to insert questions, choices and correct answers. The second table has only 1 row and stores this whole quiz as json file. When I fetch data from the first table everything is ok. I am able to retrieve the associative array correctly (later used to render radio buttons for quiz). But if I fetch data from the second table I lose array keys and can't make my quiz. Is there a way to fetch json file and make it look like the associative array from the first table? Table 1:

    $sql = "SELECT * FROM `php quizzer`";
  $result = $conn->query($sql);
   
  while($row = $result->fetch(PDO::FETCH_ASSOC)) {
      $Quiz[] = 
 array("Question" => $row['Question'], "Option" => $row['Option'], "Correct" => $row['Correct']); 

  }

Array looks like this:

Array ( [0] => Array ( [Question] => what do you like? [Option] => in, at, under, on [Correct] => in ) [1] => Array ( [Question] => How old are you? [Option] => 25, 30, 40, 34 [Correct] => 34 ) [2] => Array ( [Question] => Where is Paris? [Option] => Rome,Russia,France,Turkey [Correct] => France )

I can json encode and decode this array and output will be the same. But in Table 2:

$sql = "SELECT * FROM `quizzes`";
  $result = $conn->query($sql);

  while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$Quiz[] = $row; 

this array has only 1 key at the beginning... because of json file. Looks like this:

Array ( [Quiz] => [{"Question":"what do you like?","Option":"in, at, under, on","Correct":"in"},{"Question":"How old are you?","Option":"25, 30, 40, 34","Correct":"34"},{"Question":"Where is Paris?","Option":"Rome,Russia,France,Turkey","Correct":"France"},

How can I fetch data from the second table to get exactly the same associative array as in table 1 and keep all array keys correctly?

Michael
  • 25
  • 3
  • `json_decode($row['Quiz'])`? – Phil Feb 02 '22 at 04:59
  • Also, I recommend that you never use spaces in your db table or column names. It forces you to bloat your sql with backticks (avoidably). Also, why not `fetchAll()`? Nominate the data that you actually need instead of the lazy/greedy `*`. – mickmackusa Feb 02 '22 at 05:13

0 Answers0