Building a Simple Quiz

Published by Chris Coyier

I had to build a quiz for a client a little while ago. A few multiple choice questions, submit button, and it grades the quiz and tells you how you did. It's kinda dorky and really really simple PHP, but I figure it might be a good starter for some folks and a good primer in the basic theory of building a form in HTML and dealing with the data on another page with PHP.


View DemoDownload Files


The questions for the quiz are wrapped in a form:

<form action="grade.php" method="post" id="quiz">
   ... questions here ...

Forms typically have submit buttons, and this one is no exception. When that submit button is clicked, it will "POST" the data from each input within the form to the "action" URL provided.

Quizzes are essentially lists of questions, so an ordered list will do, so an individual question will look like this:


    <h3>CSS Stands for...</h3>
        <input type="radio" name="question-1-answers" id="question-1-answers-A" value="A" />
        <label for="question-1-answers-A">A) Computer Styled Sections </label>
        <input type="radio" name="question-1-answers" id="question-1-answers-B" value="B" />
        <label for="question-1-answers-B">B) Cascading Style Sheets</label>
        <input type="radio" name="question-1-answers" id="question-1-answers-C" value="C" />
        <label for="question-1-answers-C">C) Crazy Solid Shapes</label>
        <input type="radio" name="question-1-answers" id="question-1-answers-D" value="D" />
        <label for="question-1-answers-D">D) None of the above</label>


Notice there are four inputs there, but they all have a type of "radio" and an identical "name" attribute. They basically act as a single input that way, as only one of them can be selected at a time and the data is POSTed as single value.

At the end, our submit button:

<input type="submit" value="Submit Quiz" />

In our grade.php file, we need to grab the values that have been POSTed, then we'll check each one and increment a number correct, and finally display a div showing the number of correct answers:

    $answer1 = $_POST['question-1-answers'];
    $answer2 = $_POST['question-2-answers'];
    $answer3 = $_POST['question-3-answers'];
    $answer4 = $_POST['question-4-answers'];
    $answer5 = $_POST['question-5-answers'];

    $totalCorrect = 0;
    if ($answer1 == "B") { $totalCorrect++; }
    if ($answer2 == "A") { $totalCorrect++; }
    if ($answer3 == "C") { $totalCorrect++; }
    if ($answer4 == "D") { $totalCorrect++; }
    if ($answer5) { $totalCorrect++; }
    echo "<div id='results'>$totalCorrect / 5 correct</div>";