How can PHP handle user selections and responses in a quiz-like application with multiple pages?
To handle user selections and responses in a quiz-like application with multiple pages, you can use sessions to store the user's answers as they progress through the quiz. Each page can submit the user's answer to the server, which then stores it in the session. This way, the user's progress and answers are maintained across multiple pages.
<?php
session_start();
// Check if the user has submitted an answer
if(isset($_POST['answer'])){
// Store the user's answer in the session
$_SESSION['answers'][$_POST['question']] = $_POST['answer'];
}
// Display the quiz questions and options
$questions = array(
1 => "Question 1: What is 2 + 2?",
2 => "Question 2: What is the capital of France?",
// Add more questions here
);
foreach($questions as $questionNumber => $question){
echo "<p>$question</p>";
echo "<form method='post'>";
echo "<input type='radio' name='answer' value='A'> Option A<br>";
echo "<input type='radio' name='answer' value='B'> Option B<br>";
echo "<input type='radio' name='answer' value='C'> Option C<br>";
echo "<input type='hidden' name='question' value='$questionNumber'>";
echo "<input type='submit' value='Submit'>";
echo "</form>";
}
?>
Related Questions
- What potential pitfalls should the user be aware of when trying to access specific values within an XML file using PHP?
- What potential issue can arise when using the UPDATE statement in PHP to update multiple rows in a database?
- Is it recommended to create a function for accessing session variables in PHP for better reusability and readability?