Over a million developers have joined DZone.
Platinum Partner

Building a Simple Quiz in PHP

· Web Dev Zone

The Web Dev Zone is brought to you in partnership with Mendix.  Discover how IT departments looking for ways to keep up with demand for business apps has caused a new breed of developers to surface - the Rapid Application Developer.

Building a simple quiz is quite easy, and could be used on your website anywhere. I figured it out and found it to be very simple and easy to do.

All the steps you need to do is to create a simple form and after that a PHP Script that will calculate the answers of the specific question.

I have followed some simple steps, created a form as below.


Next step I followed is that I have simply action my form with another file “quiz_result.php”

My file will elaborate all the results and then display the correct answers on the next page.

So first of all created a form with following qualities.

<form action="quiz_result.php" method="post" id="quiz">

……..Form Here……..


Next to that I have created a simple single question with four multiple choice, I have preferred radio buttons so that user can select only single option.



<h3>HTML Stands for...</h3>


<input type="radio" name="question-1-answers" id="question-1-answers-A" value="A" />

<label for="question-1-answers-A">A) Hypertext Markup Language </label>



<input type="radio" name="question-1-answers" id="question-1-answers-B" value="B" />

<label for="question-1-answers-B">B) Hypertext Markup</label>



<input type="radio" name="question-1-answers" id="question-1-answers-C" value="C" />

<label for="question-1-answers-C">C) Hypertext Programming</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>




At the end of this form before the ending of </form> I have placed a button that will let me redirect to the next page to display the results.


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


And main thing was my PHP Script file “quiz_result.php”.


$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>";

The Web Dev Zone is brought to you in partnership with Mendix.  Learn more about The Essentials of Digital Innovation and how it needs to be at the heart of every organization.

php scripts,php tutorial

Published at DZone with permission of Mudasir Nazir Malik .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}