How to make a Trivia Game in PHP

Introduction

How to make a Trivia Game in PHP
How to make a Trivia Game in PHP

Today we will discuss on everything you need to know about How to make a Trivia Game in PHP in simple and easy to follow guide.

This is your ultimate source to quickly understand and get hands on, on how to make the Trivia game to play and enjoy with your friends.

More specifically we will discuss:

  • How to setup your environment
  • The backend PHP code
  • The frontend bootstrap/html code
  • How to make some sample questions

All the code and examples that will be provided below can be found in my git repo here.

I have been working in the Software industry for over 23 years now and I have been a software architect, manager, developer and engineer. I am a machine learning and crypto enthusiast with emphasis in security. I have experience in various industries such as entertainment, broadcasting, healthcare, security, education, retail and finance.

How to Create Trivia Questions in CSV

The first thing we need to do is create a file that has all the questions and answers we will be using in our code later on.

The goals of this file are the following:

  • Create engaging questions and answers
  • Keep the format of the questions simple
  • Use a lightweight format such as CSV that can be edited in Excel and a text editor

Having said the above lets get started and see how the format we will be creating would look like in a text representation:

How to Create Trivia Questions in CSV - Text representation
How to Create Trivia Questions in CSV – Text representation

Or if we use a handy Visual Studio Code plugin we can preview it in a visual representation as seen below. Do note you can also use excel or Openoffice/Libreoffice to edit CSV files.

How to Create Trivia Questions in CSV - Visual Representation
How to Create Trivia Questions in CSV – Visual Representation

The good thing about keeping the format simple is that you can process big files pretty fast in your code and load them into memory without taking too much space. Furthermore PHP provides an out of the box function that lets you do that too without having to write your own which we will go over later in this guide.

The first answer is always the correct one, this is to preserve simplicity and to also reduce having to add an extra column which holds the number of the correct answer. All shuffling of the answers will be handled later in the PHP code that we are going to be writing. Also having the correct answer always as the first one you simplify the readability of the document which makes it easier to maintain especially if there’s a long list that someone just has to skim through for accuracy.

How to Setup PHP using Development Server

How to Install PHP

First thing you need to do is to make sure you have PHP installed in your system. You can do either from a package manager or directly by downloading it from the PHP website here. Once you download the file you can proceed with installing PHP into your system. An important note here is that you want to make sure PHP is in your environment path. This changes based on the operating system you are running.

  • Linux: You need to add this in your PATH variable which is usually set in your shell script file (.zshrc, .bashrc, .cshrc etc)
  • Windows: You can set environment variables in Windows under your system settings in the user profile, a bonus tip here is that if you are going to be invoking PHP from the command line you can use the following too: set PATH=DIR don’t forget to append to the original Path variable too otherwise you’d be replacing the entire path part.

How to Start PHP Development Server

Now that we have ensured PHP is in our Path we need to start the development server. PHP Bundles this for debug reasons as you can see all the exceptions happening and not have to install a separate Web Server in your machine if you are just debugging. Offcourse never go into a production server using the Development PHP server this is meant entirely for debugging reasons.

I have made a shell script which could run in Linux or if you have CygWin/MSYS2 installed in Windows you can use that too from the terminal. To invoke the PHP Development server you can run the command as shown below.

main ● alex@DYNAMH ~/code/unbiased-coder/php-trivia-game > ./start_server.sh
[Mon Oct 18 22:41:19 2021] PHP 8.0.0 Development Server (http://192.168.13.57:8000) started
[Mon Oct 18 22:41:24 2021] 192.168.1.57:55985 Accepted
[Mon Oct 18 22:41:24 2021] 192.168.1.57:61649 Accepted
[Mon Oct 18 22:41:24 2021] 192.168.1.57:55985 [200]: POST /process_results.php?date=20211011&category=general
[Mon Oct 18 22:41:24 2021] 192.168.1.57:55985 Closing
[Mon Oct 18 22:41:24 2021] 192.168.1.57:61649 [200]: POST /css/bootstrap.min.css

As it can be seen above this starts PHP on port 8000 on the local IP of the computer. The actual command it’s executing is the following:

#!/bin/bash
php -S 192.168.13.57:8000

This starts the development server on the specified IP and starts receiving requests as shown above.

If you are using Windows simply invoke using the same command but instead of running the helper shell script just invoke the command directly from your terminal.

Now you should be able to see all the requests being made by the app which we will code below. Furthermore any exceptions/problems will also be displayed in the terminal so you can easily diagnose and fix any problems that may rise.

How to make a Trivia Game in PHP code

We will break down this in two different parts:

  • Frontend: All UI related code that the user interacts with
  • Backend: All Trivia logic that shows the questions and processes your answers

How to make a Trivia Game Web Page in Bootstrap

In this section we are going to discuss on how to make a Trivia Game Web Page using Bootstrap. The reason we selected Bootstrap is that it’s a lightweight framework that tends to load fast and provides us with simple and easy to use components for a Trivia Game. This article will not focus too much on the frontend side of things but we will go over some parts we need to do to make it look pretty.

How to include Bootstrap in the code

There’s two things we need to include from Bootstrap to get started in our code:

  • CSS library: This contains all the CSS classes that we can re-use in our code to make things pretty
  • JS library: This contains all the JS code, functions and transformational effects we are planning to include in our project

Including bootstrap in your project is fairly easy. Head to their website and download the latest version which you can find here.

Once you do this you will need two files from the archived package:

  • bootstrap.bundle.min.js
  • bootstrap.min.css

To include these two you can use the sample code below:

How to make a Trivia Game in PHP
How to make a Trivia Game in PHP

All of this code can also be found in the projects GIT repo here. Once you include the link in the head section of your HTML and the SCRIPT inside your body you should be good to go to start using Bootstrap in your project.

One important thing to note here is that you need to include those two files in every single HTML file you are planning to leverage bootstrap. If your project is already segregated in a way that it has a re-useable header then you can add that code there simply once. This is beyond the scope of this tutorial so we will skip it for now. If you still want to know how to do this drop me a line in the comments below and I’ll help you out.

To quickly summarize the frontend code basically uses the following bootstrap components to display things in a pretty way:

  • Bootstrap cards (to display sections of question and answers)
  • Navbar (in order to show header and later if you need more items such as a timer)
  • Traditional buttons (this is for the send questions and the answer blocks)
  • Various coloring classes

One special note must be given to using a custom style for the button animation when the mouse hovers over and out of it. The code for this can be found in the custom style.css bundled in the GIT repo. The interesting part that accomplishes that effect can be seen in the code sniper below:

.cyan-button {
    font-family: w3-cursive;
    font-weight: bold;
    color: whitesmoke;
    font-size: larger;
    transition-duration: 0.4s;
}
.cyan-button:hover {
    color: darkslategray;
    box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);
}

The key elements there that dictate the effect are the following:

  • transition-duration: This tells CSS rendering how quickly to perform the hover effect
  • box-shadow: This hooks in the hover CSS event to change the coloring of a shadow around the box

These are handy effects since they don’t require any additional Javascript code to take into effect instead CSS events are leveraged to implement it.

How to make a Trivia Game Backend

Now that we have Bootstrap setup in our code we will start discussing on how to create two pages that will handle all the logic for our Trivia game.

  • generate_questions.php: This code will basically read in the questions from our CSV file and display them to the user
  • process_results.php: This code will take in the answers from the previous page and show a score for the quiz to the user

Lets start by breaking those two files out and write the code to implement our Trivia Game. As discussed earlier this is all done using PHP without leveraging any framework or libraries other than those built-in into the language itself. The reason I went with PHP is that it integrates easily with WordPress and I wanted to include this as part of one of my other Blogs.

My code has some extensions such as leveraging WordPress authentication and registration along with some details to allow a user to have a profile and be more interactive with the game. This is not covered here and this article will strictly describe how to build the game. However if you are interested in those extensions too I would be happy to write another article about them, please let me know in the comments below if you would like to see that.

Trivia API Requests

We will be implementing two Trivia API Requests:

/generate_questions.php
        method: GET
        params:
            category: string (example: general)
            date: string (example: 20210321)
/process_results.php
        method: POST
        params:
            category: string (example: general)
            date: string (example: 20210321)
            trivia questions and answers

The parameters and details about what each of them does will be discussed below in more detail. A few important things to note here is that the naming of the PHP file matches that of the API request URL so for example accessing process_results.php the following URL should be used:

https://localip:8000/process_results.php?date=20210328&category=general

This just sets the date to 03-28-2021 and the Trivia category to General. Along with that the form data will also be sent from the previous page to contain the answers and questions that were submitted. All actions are done server side to have some basic form of security. So the answer set is randomized and shuffled before it gets sent to the client. This is done because if we were to use the Answers to the questions as is the first answer would always be the same as this is what we are using in our CSV format.

How to Generate a WebPage from Trivia Questions

To accomplish this we need to do the following steps:

  • Read the GET request parameters in our case we will be receiving the following two:
    • Date: This is the date of the file where the questions where made
    • Category: The trivial category the questions are for
  • Read the CSV contents into a PHP array
  • Display this in a pretty format using bootstrap

Getting into more specifics now the reason we need a GET request is because we want to keep a folder structure in our disk organized to store the questions. Also if we want to issue new questions sets a different date is necessary. For the category this is self explanatory the idea behind it is to know which fields each question is at. If you have a good mix you can use a generic such as a General category.

The code that implements the above can be found in the git repo here. Below you can see a small snipet which basically initializes the work we wanted to implement.

require __DIR__ . '/csv_helper.php';
require __DIR__ . '/request_helper.php';

[$date, $category] = get_category_date();
$csv = get_csv_into_array($date, $category);
$capital_category = ucfirst($category);

The get_csv_into_array function is what loads the CSV file into an array in memory. After that we take the array and load it into a bootstrap enabled html code generation.

One thing to note here there’s helper functions that read the parameters and validate them from the GET request. Those can be found in the request_helper.php file.

If we navigate to the page we should be able to see our Trivia questions loaded up and displayed with all the answers, along with a Submit button. A screenshot of how this looks like is shown below.

How to make a Trivia Game in PHP
How to make a Trivia Game in PHP

A few things to note here:

  • The URL is not showing secure because we are using the PHP development server
  • The parameters we are passing are for the sample CSV file we mentioned earlier

How to show the results of the Trivia Game Questions

One of the basic things of anyone wanting to implement a Trivia Game in PHP is giving some feedback to the user as to how well or bad they did along with educating them. So in this section we will show how to implement getting a quizz result in terms of a percentage along with educating them by showing them the correct answer to the question.

This second API is basically receiving the answers from the previous request and presenting them back to the user. The tasks we need to perform for this action are as follows:

  • Process again the CSV file into memory (similar as before). This is necessary in order to validate the answers
  • Compare the answers sent with the ones of the CSV file
  • Calculate a percentage of how many they answered correct

In order to do this we will implement the code as shown below.

$question_number = 0;
$correct = 0;
$wrong = 0;

foreach($csv as $row){
    $answer = $row[1];
    if(!strcmp($answer, $_POST[$question_number])){
        echo "'Correct - $row[0]\n";
        $correct++;
    }
    else {
        echo "Wrong - $row[0]\n";
        echo "- Answer: $answer";
        $wrong++;
    }
    $question_number++;
}

if ($correct == 0)
    $score = "0";
else
    $score = round((($correct / $question_number)*100), 2);

As it can be seen here we are iterating again answer by answer and comparing the correct one to the one submitted. Since in the CSV format we always put the correct one first (not when it’s displayed in the page but in the CSV) we know which one to pick as the correct answer. Once this is done then it’s compared to what the user submitted from the previous page. If there’s a match then it means they got the answer correct.

In order to calculate the percentage of how many they got correct we simply divide the correct answers to the total questions we found in the CSV and multiplying it by 100 as shown above to convert it into a percent. Furthermore we are using the round function here to minimize the decimal points to only 2.

If we were to send the answers from the previous page we should see something like the screen below.

Trivia Question Results
Trivia Question Results

Again the coloring and effects are bootstrap. The entire code base for this can be found in the GIT repo here. In this case we submitted 2 questions correct and 1 wrong. Obviously if you would like to have more questions in your Trivia game all you have to do is expand your CSV file with as many as you’d like as long as you preserve the format as discussed earlier.

Conclusion

If you found How to make a Trivia Game in PHP useful and you think it may have helped you please drop me a cheer below I would appreciate it.

If you have any questions, comments please post them below I check periodically and try to answer them in the priority they come in.
Also if you have any corrections please do let me know and I’ll update the article with new updates or mistakes I did.

Which is your favorite Trivia Question?

If you are considering of using a different web framework to implement this for example in Python you can check my guides on Django here:

Leave a Comment

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