I am making a basic quiz program, that when finished will allow the user to complete quizzes being read from a MySQL database, and write quizzes to be stored in the database.
I have a variable for question number ($qn
), which when incremented changes the question, and the four possible choices to the next question in the database.
My question is: How can I have a button on my main form, that (once the user has selected a radio button) recordes the radio button result, then increments $qn
to display the next question, then does that process again, until $qn == $numberOfQuestions
, at that point it needs to show the page results.php and add up the results from all the radio buttons on the quiz.php page.
I am quite new to PHP, so sorry if this is a particularly stupid question, or if I have worded it in an unclear way. And I am very open to suggestions is there is an easier or more efficient way of doing this.
Thank you in advance for any answers, really grateful :)
You just process the forms input, store the value and continue to the next question.
A rudimentary example (Demo):
<h1>Quiz</h1>
<?php
$quiz = load_quiz();
$states = isset($_GET['state']) ? explode(',', $_GET['state']) : array();
$states = array_map('intval', $states);
$page = count($states)+1;
if (isset($_POST['answer']))
{
$states[$page-1] = (int) $_POST['answer'];
}
if ($page > count($quiz))
{
?>
<h2>Your selection:</h2>
<?php
foreach($quiz as $key => $question)
{
$state = $states[$key];
$answer = $question['answers'][$state];
printf('%s: %s<br />', $question['question'], $answer);
}
}
else
{
?>
<h2><?php echo $quiz[$page]['question']; ?></h2>
<form method="post" action="?state=<?php echo implode(',', $states); ?>">
<?php
foreach($quiz[$page]['answers'] as $key => $answer)
{
printf(
'<input type="radio" name="answer" id="answer-%d" value="%d"><label for="answer-%d">%s<label><br>',
$key, $key, $key, $answer
);
}
?>
<input type="submit" value="Next">
</form>