php quiz code with database

Here is an example of a PHP quiz code that stores the quiz questions and answers in a MySQL database:


// Connect to the database
$host = "localhost";
$username = "username";
$password = "password";
$dbname = "quiz";

$conn = mysqli_connect($host, $username, $password, $dbname);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());

// Initialize variables
$total_questions = 0;
$total_correct = 0;

// Get the quiz questions and answers from the database
$query = "SELECT * FROM quiz_questions";
$result = mysqli_query($conn, $query);

while ($row = mysqli_fetch_assoc($result)) {
    // Increment the total number of questions

    // Print the question
    echo $row['question'] . "<br>";

    // Print the options
    echo "<input type='radio' name='q" . $total_questions . "' value='a'>" . $row['option_a'] . "<br>";
    echo "<input type='radio' name='q" . $total_questions . "' value='b'>" . $row['option_b'] . "<br>";
    echo "<input type='radio' name='q" . $total_questions . "' value='c'>" . $row['option_c'] . "<br>";
    echo "<input type='radio' name='q" . $total_questions . "' value='d'>" . $row['option_d'] . "<br>";

    // Check if the submitted answer is correct
    if ($_POST['q' . $total_questions] == $row['answer']) {

// Calculate the percentage of correct answers
$percent_correct = ($total_correct / $total_questions) * 100;

// Print the results
echo "You got " . $total_correct . " out of " . $total_questions . " correct (" . $percent_correct . "%)";



This code assumes that you have a MySQL database with a table called quiz_questions that has the following columns: id, question, option_a, option_b, option_c, option_d, and answer. The id column is an auto-incrementing primary key, and the answer column contains the correct answer to the question (either ‘a’, ‘b’, ‘c’, or ‘d’).

To use this code, you will need to replace username, password, and quiz with the appropriate values for your MySQL database.

This code also assumes that you are using an HTML form to submit the quiz answers. Each question is represented by a set of radio buttons, with the name attribute set to “q1”, “q2”, etc. depending on the question number. When the form is submitted, the PHP script will loop through the submitted answers and check if they are correct by comparing them to the answers stored in the database. Finally, it will calculate the percentage of correct answers and print the results.

Leave a Comment