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!

 

 

TABLE OF CONTENTS

 

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 flags 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()">

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

EXTRA 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!

2 thoughts on “Simple PHP Quiz Without Database (Free Download)”

  1. Hello.
    Thank you for this simple quiz, I use this to give my kids and their friends something cool to make when they stay on PC, we make a quiz night every few weeks.
    Some suggestions that can make it even more cool:
    – add an image for question, so I can add something like “What animal is this?” and show a lion image etc …
    -add a timer for every question, eg : 30s pass without any answer, marked at wrong answer and skip to next question
    -if refresh the page, quiz should stay on same question, on the left timer ; not starting again with first question.
    -life options, for every quiz started you have 3 options like :
    + 50/50 – remove 2 wrong answers
    + skip question – marked as correct answer and skip to next question
    + extra time – add extra seconds to answer to this question

    I think it is easy for you to make these changes and updates.
    Best Regards,
    Cosmin K.

Leave a Comment

Your email address will not be published. Required fields are marked *