etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

How to create a multiple choice quiz in PHP and MySQL

In this article, you will learn how to create a multiple-choice quiz in PHP and MySQL. Today, online quizzes have a lot of advantages. It is considered an easy way to conduct a quiz, engage your audience, large number of participants and randomise questions. It is also advantageous for the security and confidentiality of quiz questions and answers; no instructor is required. It also saves paper, time, and money, and it's more secure.





Creating Database

A database needs to be created to store the information about questions, options, and correct answers. So let's create a database using the following query. Here is a table 'questions' that contains all the quiz questions.

CREATE TABLE IF NOT EXISTS `questions` (
  `qid` int(11) NOT NULL AUTO_INCREMENT,
  `question` varchar(150) NOT NULL,
  `is_enabled` int(11) NOT NULL,
  PRIMARY KEY (`qid`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
INSERT INTO `questions` (`qid`, `question`, `is_enabled`) VALUES
(1, 'Which function is used to reverse the order of elements in an array?', 1),
(2, 'Which function is used to return character from the ASCII value?', 1),
(3, 'Which function is used to check the existence of a constant?', 1),
(4, 'Which function is used to return the last element of an array?', 1);

Here is a table 'quiz_options' that contains all the quiz options-

CREATE TABLE IF NOT EXISTS `quiz_options` (
  `option_id` int(11) NOT NULL AUTO_INCREMENT,
  `qid` int(11) NOT NULL,
  `option` varchar(150) NOT NULL,
  `is_enabled` int(11) NOT NULL,
  PRIMARY KEY (`option_id`)
) ENGINE=MyISAM AUTO_INCREMENT=17 DEFAULT CHARSET=latin1;
INSERT INTO `quiz_options` (`option_id`, `qid`, `option`, `is_enabled`) VALUES
(1, 1, 'array_rev()', 1),
(2, 1, 'array_reverse()', 1),
(3, 1, 'reverse()', 1),
(4, 1, 'array_end()', 1),
(5, 2, 'chr()', 1),
(6, 2, 'ascii()', 1),
(7, 2, 'asc()', 1),
(8, 2, 'return_chr()', 1),
(9, 3, 'define()', 1),
(10, 3, 'const()', 1),
(11, 3, 'defined()', 1),
(12, 3, 'exist()', 1),
(13, 4, 'end()', 1),
(14, 4, 'arr_end()', 1),
(15, 4, 'last()', 1),
(16, 4, 'end()', 1);

Finally, we create a table 'quiz_answer' for storing the correct answer to the quiz-

CREATE TABLE IF NOT EXISTS `quiz_answer` (
  `qa_id` int(11) NOT NULL AUTO_INCREMENT,
  `qid` int(11) NOT NULL,
  `option_number` int(11) NOT NULL,
  PRIMARY KEY (`qa_id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
INSERT INTO `quiz_answer` (`qa_id`, `qid`, `option_number`) VALUES
(1, 1, 2),
(2, 2, 1),
(3, 3, 3),
(4, 4, 4);




Source Code

These are the PHP source codes for multiple-choice questions and answers. For simplicity, we have used MySQLi object-oriented programming to simplify the database connection code.

quizclass.php

First, we have taken variables for database credentials. Please replace them with your credentials. Next, we have a constructor function for database connectivity code.

<?php

class Quiz {
// Database credentials
private $host     = 'hostname';
private $username = 'username';
private $password = 'password';
private $database = 'dbname';
public  $db;

public function __construct(){
if(!isset($this->db)){
	// Connect to the database    
	try {
	$this->db = new mysqli($this->host, $this->username, $this->password, $this->database);
	}catch (Exception $e){
	$error = $e->getMessage();
	echo $error;
	}
}
}
public function get_questions(){
 $select = "SELECT * FROM `questions` where is_enabled = '1' ";
 $result = mysqli_query($this->db ,$select);
 return mysqli_fetch_all($result);
}
public function quiz_options($qid) {
 $select = "SELECT * FROM `quiz_options` where qid = '$qid' AND is_enabled = '1'  ";
 $result = mysqli_query($this->db ,$select);
 return mysqli_fetch_all($result);
} 
public function answer($qid) {
 $select = "SELECT * FROM `quiz_answer` where qid = '$qid' ";
 $result = mysqli_query($this->db ,$select);
 return mysqli_fetch_all($result);
} 
}
?>




index.php

This is the main file that we will call in the browser. In this, we have imported the 'quizclass.php' and looped over the questions and options data. When the user submits the form, it will redirect to the 'score.php' page.

<html>
<head>
<title>PHP Multiple Choice Questions and Answers</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<?php
	include 'quizclass.php';
	$db = new Quiz();
	$quesions = $db->get_questions();

?>
<div class="container">
<h1>Multiple Choice Questions Answers</h1>
<p>Please fill the details and answers the all questions-</p>
<div class="form-group">
<form action="score.php" method="post">
<?php
foreach($quesions as $ques) {
$options = $db->quiz_options($ques[0]);

?>
<h4><?php echo $ques[1]; ?></h4>
<div class="input-group-text" style="text-align: left; font-size: 18px;"> 
<ol>
<?php
foreach($options as $option) { 
 echo "<li><input type='radio' name='".$option[2]."' value='".$option[1]."' required/> ".$option[3]."</li>";
}
?>
</ol>
</div>

</div>
<div class="form-group">
<input type="submit" value="Submit" name="submit" class="btn btn-primary"/>
</div>
</form>
</div>
</body>
</html>




score.php

On this page, we collect the post data and calculate the user's score. For this, we have imported the 'quizclass.php' database class file and compared the correct answer with the user's.

<?php 
include 'quizclass.php';
$db = new Quiz();
$score = 0;
foreach($_POST as $k=>$v)
{
	$answer = $db->answer($k);
	if($answer[0][2] == $v) { // option is correct
		$score++;
	}
}
$score = $score	/ 4 *100;
if($score < 50)
{
	echo '<h2>You need to score at least 50% to pass the exam.</h2>';
}
else {
	echo '<h2>You have passed the exam and scored '.$score.'%.</h2>';
}
?>




Related Articles

Import Data Into MySQL From Excel File
Php display PDF in iframe
Read CSV file & Import data into MySQL with PHP
How to create a doc file using PHP
PHP | SplFileObject fread() Function
File upload in PHP MySQL database
Send HTML form data to email using PHP
Forgot password code in PHP mysqli
PHP Basic authentication example
PHP cache example
PHP get current directory path
How to prevent CSRF attack in PHP
PHP contact form send email SMTP
Dynamic pagination in PHP
File upload ftp PHP
Insert image in database using PHP
PHP sanitize input for MySQL
Simple pagination in PHP with MySQL
Store Emoji character in MySQL using PHP
Insert in database without page refresh PHP




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
PHP code to send email using SMTP
-----------------
Hypertext Transfer Protocol Overview
-----------------
How to encrypt password in PHP
-----------------
Characteristics of a Good Computer Program
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to get current directory, filename and code line number in PHP
-----------------
How to add multiple custom markers on google map
-----------------
Fibonacci Series Program in PHP
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
How to generate QR Code in PHP
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
Simple pagination in PHP
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP Server Side Form Validation
-----------------
PHP MYSQL Advanced Search Feature
-----------------
Simple way to send SMTP mail using Node.js
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
Simple PHP File Cache
-----------------
PHP Secure User Registration with Login/logout
-----------------
jQuery File upload progress bar with file size validation
-----------------
Simple File Upload Script in PHP
-----------------
Php file based authentication
-----------------
Calculate distance between two locations using PHP
-----------------
PHP User Authentication by IP Address
-----------------
To check whether a year is a leap year or not in php
-----------------
How to print specific part of a web page in javascript
-----------------
Simple Show Hide Menu Navigation
-----------------
Detect Mobile Devices in PHP
-----------------
PHP Sending HTML form data to an Email
-----------------
Polling system using PHP, Ajax and MySql
-----------------
Google Street View API Example
-----------------
SQL Injection Prevention Techniques
-----------------
Get Visitor\'s location and TimeZone
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Convert MySQL to JSON using PHP
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
Set and Get Cookies in PHP
-----------------
PHP Programming Error Types
-----------------
CSS Simple Menu Navigation Bar
-----------------
Date Timestamp Formats in PHP
-----------------
How to add google map on your website and display address on click marker
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
Write a python program to print all even numbers between 1 to 100
-----------------
How to display PDF file in web page from Database in PHP
-----------------
PHP Getting Document of Remote Address
-----------------
File Upload Validation in PHP
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial






Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2023. All Rights Reserved.