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 FilePhp 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