Simple PHP Quiz Without Database (Free Download)

Welcome to a tutorial on how to create a quiz in PHP. Want to add a quiz to your website, but don’t need all the crazy admin features and stuff? Here’s a quick sharing of my simple version, without a database – Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

Download & Notes PHP Quiz Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • Just launch 2-quiz.html in your browser. Use http://, not file://.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

PHP QUIZ

All right, let us now get into the ways to create a simple quiz in PHP.

 

STEP 1) QUESTIONS & ANSWERS

1-qna.php
<?php
$quiz = [
  [
    "q" => "Which is the biggest island in the world?",
    "o" => ["Bora Bora", "Greenland", "Bali", "Borneo"],
    "a" => 1
  ],
  [
    "q" => "Which country produces the most coffee?",
    "o" => ["India", "Vietnam", "Brazil", "Indonesia"],
    "a" => 2
  ],
  [
    "q" => "Which country has the most vending machines?",
    "o" => ["Japan", "US", "Singapore", "Russia"],
    "a" => 0
  ],
  [
    "q" => "How long does it take for food to pass through the human body?",
    "o" => ["12 hours", "26 hours", "47 hours", "53 hours"],
    "a" => 3
  ]
];

Since we don’t have a database, the only way is to store the questions and answers in an array. This should be pretty self-explanatory.

  • q The question itself.
  • o The available options. Take note, you can have as many options as you like. It does not have to be exactly 4.
  • a Which option is the correct answer. Take note again, an array starts with index 0. So 0 states that the first option is correct.

 

STEP 2) QUIZ PAGE

quiz.html
<div id="quizWrap">
  <div id="quizQn"></div>
  <div id="quizAns"></div>
</div>

Yep, that’s all. The rest will be generated with Javascript.

  • quizWrap The quiz wrapper itself.
  • quizQn The current question.
  • quizAns To place all the available options.

 

 

STEP 3) AJAX HANDLER

3-ajax.php
<?php
if (isset($_POST["qn"])) {
  // (A) LOAD QUESTIONS & ANSWERS
  require "1-qna.php";
 
  // (B) FIRST QUESTION ONLY - ALSO RETURN TOTAL # OF QUESTIONS
  if ($_POST["qn"]==0) {
    $qn = $quiz[0];
    $qn["all"] = count($quiz);
    echo json_encode($qn);
  }
 
  // (C) OUTPUT QUESTION
  else { echo json_encode($quiz[$_POST["qn"]]); }
}

As stated, we will deal with the questions and answers with Javascript. But first, here’s a simple PHP-AJAX handler to get the question/options themselves. Should be self-explanatory again:

  • We simply send a  $_POST["qn"] to this script to get the selected question/options.
  • Just a small note. On the first question $_POST["qn"]==0, we will return the total number of questions count($quiz).

 

STEP 4) THE JAVASCRIPT

4A) QUIZ PROPERTIES

4-quiz.js
// (A) PROPERTIES
// (A1) HTML ELEMENTS
hQn : null, // question <div>
hAns : null, // answer <div>
 
// (A2) QUIZ FLAGS
all : 0, // total number of questions
now : 0, // current question
ans : 0, // current correct answer
score : 0, // current score

The Javascript is probably the most confusing part. Not going to explain line-by-line, but all these flag are necessary to drive the quiz.

 

 

4B) QUIZ INIT

4-quiz.js
// (B) INIT QUIZ
init : () => {
  quiz.hQn = document.getElementById("quizQn");
  quiz.hAns = document.getElementById("quizAns");
  quiz.load();
}
window.addEventListener("DOMContentLoaded", quiz.init);

quiz.init() is the first thing that will run on page load. All it does is to get the question and options HTML <div>, then proceed to load the first question.

 

4C) LOAD THE NEXT QUESTION

4-quiz.js
// (C) LOAD NEXT QUESTION/ANSWER
load : () => {
  // (C1) FORM DATA
  let data = new FormData();
  data.append("qn", quiz.now);
 
  // (C2) AJAX FETCH
  fetch("3-ajax.php", { method:"POST", body:data })
  .then(res => res.json()).then((qna) => {
    // TOTAL NUMBER OF QUESTIONS
    if (quiz.now == 0) { quiz.all = qna.all; }
 
    // SET THE QUESTION
    quiz.hQn.innerHTML = qna.q;
 
    // SET THE OPTIONS
    quiz.ans = qna.a;
    quiz.hAns.innerHTML = "";
    qna.o.forEach((val, idx) => {
      let o = document.createElement("div");
      o.className = "option";
      o.id = "opt"+idx;
      o.innerHTML = val;
      o.onclick = () => { quiz.pick(idx); };
      quiz.hAns.appendChild(o);
    });
  });
}

This is quite a bit of code, but keep calm and look carefully.

  • (A2) We use the quiz.now flag to track the current question number.
  • (C1) We need to pass this flag to 3-ajax.php to get the correct question and options.
  • (C2) Send quiz.now to 3-ajax.php. Draw the question and options.

Yep, that’s about it.

4D) PICK AN OPTION

4-quiz.js
 // (D) PICK AN OPTION
pick : (idx) => {
  // (D1) DETACH ALL ONCLICK & SET RIGHT/WRONG CSS
  for (let o of quiz.hAns.getElementsByClassName("option")) {
    o.onclick = "";
  }
 
  // (D2) CORRECT ANSWER?
  let o = document.getElementById("opt"+idx);
  if (idx == quiz.ans) {
    quiz.score++;
    o.classList.add("correct");
  } else {
    o.classList.add("wrong");
  }
 
  // (D3) NEXT QUESTION OR END GAME
  quiz.now++;
  setTimeout(() => {
    if (quiz.now < quiz.all) { quiz.load(); }
    else {
      quiz.hQn.innerHTML = `You have answered ${quiz.score} of ${quiz.all} correctly.`;
      quiz.hAns.innerHTML = "";
    }
  }, 1000);
}

This is what happens when the user picks an option.

  • Update the score quiz.score.
  • Update the current question number quiz.now.
  • Load the next question.

It’s actually simple, but just long-winded.

 

 

4E) RESET THE QUIZ

4-quiz.js
 // (E) RESET QUIZ
reset : () => {
  quiz.all = 0;
  quiz.now = 0;
  quiz.ans = 0;
  quiz.score = 0;
  quiz.draw();
}

For you guys who need to reset the quiz – Just call quiz.reset(). Maybe this into the end of the quiz, something like this in (D3) – <input type="button" value="Try Again" onclick="quiz.reset()"/>

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

COMPATIBILITY CHECKS

This quiz should work on all modern “Grade A” browsers.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published.