What is the best practice for storing user answers in a session when dealing with dynamic quiz forms in PHP?
When dealing with dynamic quiz forms in PHP, the best practice for storing user answers in a session is to use an associative array to keep track of the answers for each question. This allows for easy retrieval and updating of answers as the user progresses through the quiz.
// Start the session
session_start();
// Initialize an empty array to store user answers
if(!isset($_SESSION['user_answers'])) {
$_SESSION['user_answers'] = [];
}
// Update user answers based on form submission
if($_SERVER['REQUEST_METHOD'] == 'POST') {
foreach($_POST as $question_id => $answer) {
$_SESSION['user_answers'][$question_id] = $answer;
}
}
// Retrieve user answers for a specific question
function getUserAnswer($question_id) {
if(isset($_SESSION['user_answers'][$question_id])) {
return $_SESSION['user_answers'][$question_id];
} else {
return null;
}
}
Keywords
Related Questions
- Are there any alternative approaches to using PHP for dynamically changing stylesheets based on the season?
- What are the security considerations when extracting data from a foreign website using PHP?
- How can the presence or absence of specific columns in database tables affect the execution of SQL queries in PHP?