What are some best practices for storing and retrieving data from a database in PHP for quiz creation?

When creating a quiz in PHP, it's important to store the quiz questions and answers in a database for easy retrieval and management. One best practice is to create a database table specifically for storing quiz questions and another table for storing the answers associated with each question. This allows for efficient querying and organizing of quiz data.

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

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

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

// Retrieve quiz questions from the database
$sql = "SELECT * FROM quiz_questions";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        // Output each question
        echo "Question: " . $row["question_text"] . "<br>";

        // Retrieve answers for the current question
        $question_id = $row["question_id"];
        $answers_sql = "SELECT * FROM quiz_answers WHERE question_id = $question_id";
        $answers_result = $conn->query($answers_sql);

        if ($answers_result->num_rows > 0) {
            while($answer_row = $answers_result->fetch_assoc()) {
                // Output each answer
                echo "Answer: " . $answer_row["answer_text"] . "<br>";
            }
        }
    }
} else {
    echo "0 results";
}

// Close connection
$conn->close();