I want to create some online quizzes using values stored in a database table. Each page will display ten questions, with each question followed by four possible answers...
What color are apples?
red
yellow
blue
pink
I know how to make a simple array that will display all the questions. Or I can display all the answers. But grouping each set of answers with the appropriate answer is trickier.
Someone suggested I use a multidimensional array combined with foreach. So I started checking out some related threads, including the one @ php PDO fetchAll() - while not working, foreach works but I'm completely snowed.
This is what I've come up with so far...
$Questions = array('question' => $Question, 'answers' => array($Answers));
foreach ($Questions as $Question => $Answers) {
echo $Questions.'<br />';
}
But it probably has more errors than I can count. Is this at least on the right track?
I posted my code below.
$stmt = $pdo->prepare("SELECT T.URL, TQ.URL, TQ.QID, TQ.Question, TQ.Feedback, TA.URL, TA.QID QID2, TA.Value, TA.Answer, TA.Correct
FROM g_tests T
LEFT JOIN g_test_questions TQ ON TQ.URL = T.URL
LEFT JOIN g_test_answers TA ON TA.URL = T.URL
WHERE T.URL = 'gw-intro-1' AND TQ.QID = TA.QID
ORDER BY TA.N");
$stmt->execute(array(
'MyURL'=>$MyURL
));
while ($row = $stmt->fetch()) {
$URL = $row['URL'];
$QID = $row['QID'];
$QID2 = $row['QID2'];
$Question = $row['Question'];
$Feedback = $row['Feedback'];
$Value = $row['Value'];
$Answer = $row['Answer'];
$Correct = $row['Correct'];
$Correct = str_replace('1', 'correct', $Correct);
$Correct = str_replace('2', 'wrong', $Correct);
$Questions = array('question' => $Question, 'answers' => array($Answers));
foreach ($Questions as $Question => $Answers) {
echo $Questions.'<br />';
}
}
I edited this to show my revised code:
$stmt = $pdo->prepare("SELECT T.Site, T.Type, T.URL, T.Section, T.URL_Foreign, T.Title, T.Subtitle, T.Parent, T.Live, TQ.URL, TQ.QID, TQ.Question, TQ.Feedback, TA.URL, TA.QID QID2, TA.Value, TA.Answer, TA.Correct
FROM g_tests T
LEFT JOIN g_test_questions TQ ON TQ.URL = T.URL
LEFT JOIN g_test_answers TA ON TA.URL = T.URL
WHERE T.URL = 'gw-intro-1' AND TQ.QID = TA.QID
ORDER BY TA.N");
$stmt->execute(array('MyURL' => $MyURL));
$Array = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($Array as $dataset){
foreach ($dataset as $Column => $Value){
echo "The column [$Column] contains [$Value] <br> \r\n";
}
}