What are the advantages of storing quiz answers in a database rather than using sessions in PHP?

Storing quiz answers in a database rather than using sessions in PHP allows for better data management, scalability, and security. By storing answers in a database, you can easily retrieve and analyze the data, handle a large number of users simultaneously, and ensure that sensitive information is securely stored.

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "quiz_answers";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Store quiz answers in the database
$user_id = $_SESSION['user_id'];
$question_id = $_POST['question_id'];
$answer = $_POST['answer'];

$sql = "INSERT INTO answers (user_id, question_id, answer) VALUES ('$user_id', '$question_id', '$answer')";

if ($conn->query($sql) === TRUE) {
    echo "Answer stored successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();