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
- How can the unsatisfactory programming structure of the provided code be improved to ensure cleaner and more efficient functionality?
- Why is it recommended to avoid using SELECT * in database queries in PHP?
- How can the code structure be improved to ensure all rows of data are included in the CSV file download in PHP?