Quiz application Using PHP, jQuery, Ajax, MySQL and HTML5
Everyone likes to make some hello world application, here is that type application you can make it youself.
I am going to make Quiz application using PHP, MySQL, HTML5, jQuery, Ajax and CSS3. Just follow this tutorial to make it this appliaction youself. At the end of this tutorial you are going to have nice working your Quiz Application.
Note : You can refer my latest Quiz application
Responsive PHP Quiz Script
Here is the folder structure of the application.
Quiz
├── ajax.php
├── config.php
├── css
│ ├── Lobster.otf
│ └── style.css
├── functions.php
├── index.php
├── js
│ ├── app.js
│ ├── jquery-1.9.1.min.js
│ └── watch.js
├── questions.sql
└── results.jpg
Step 1:
Create a table for your Quiz application using following SQL Queries.
CREATE TABLE IF NOT EXISTS `questions` ( `id` int(11) NOT NULL AUTO_INCREMENT, `question_name` text NOT NULL, `answer1` varchar(50) NOT NULL, `answer2` varchar(50) NOT NULL, `answer3` varchar(50) NOT NULL, `answer4` varchar(50) NOT NULL, `answer` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
Now insert some sample data’s in it.
INSERT INTO `questions` (`id`, `question_name`, `answer1`, `answer2`, `answer3`, `answer4`, `answer`) VALUES (1, 'What does PHP stand for?', 'Personal Home Page', 'Personal Hypertext Processor', 'Private Home Page', 'PHP: Hypertext Preprocessor', '4'), (2, 'How do you write "Hello World" in PHP', 'Document.Write("Hello World");', 'echo "Hello World";', '"Hello World";', '"Hello World";', '2'), (3, 'The PHP syntax is most similar to:', 'VBScript', 'JavaScript', 'Perl and C', 'Perl and C', '3'), (4, 'How do you get information from a form that is submitted using the "get" method?', 'Request.Form;', '$_GET[];', 'Request.QueryString;', 'Request.QueryString;', '2');
Step 2:
Create config.php file to write database connection at one place.
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'smarttut_developersguide');
define('DB_USER','xyz');
define('DB_PASSWORD','mysql');
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
Step 3:
Now create index.php file, and include config.php & functions.php files at the first and call getQuestions() function to get list of Questions.
<?php
require_once 'config.php';
require_once 'functions.php';
$qestions = getQuestions();
?>
now html part. I added stylesheet in the head section and h1 tag in the body.
<!DOCTYPE html>
<html>
<head>
<title>PHP Quiz Application Using jQuery, Ajax and MySQL</title>
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel='stylesheet' href='css/style.css'/>
</head>
<body>
<h1>Quiz using PHP, jQuery, Ajax and MySQL</h1>
Next dynamically generate form fields for all questions.
<form method='post' id='quiz_form'>
<?php foreach ($qestions as $key => $qestion) { ?>
<div id="question_<?php echo $qestion['id'];?>" class='questions'>
<h2 id="question_<?php echo $qestion['id'];?>"><?php echo $qestion['id'].".".$qestion['question_name'];?></h2>
<div class='align'>
<div class="question-container">
<input type="radio" value="1" id='radio1_<?php echo $qestion['id'];?>' name='<?php echo $qestion['id'];?>'>
<label id='ans1_<?php echo $qestion['id'];?>' for='1'><?php echo $qestion['answer1'];?></label>
</div>
<div class="question-container">
<input type="radio" value="2" id='radio2_<?php echo $qestion['id'];?>' name='<?php echo $qestion['id'];?>'>
<label id='ans2_<?php echo $qestion['id'];?>' for='1'><?php echo $qestion['answer2'];?></label>
</div>
<div class="question-container">
<input type="radio" value="3" id='radio3_<?php echo $qestion['id'];?>' name='<?php echo $qestion['id'];?>'>
<label id='ans3_<?php echo $qestion['id'];?>' for='1'><?php echo $qestion['answer3'];?></label>
</div>
<div class="question-container">
<input type="radio" value="4" id='radio4_<?php echo $qestion['id'];?>' name='<?php echo $qestion['id'];?>'>
<label id='ans4_<?php echo $qestion['id'];?>' for='1'><?php echo $qestion['answer4'];?></label>
<input type="radio" checked='checked' value="5" style='display:none' id='radio4_<?php echo $qestion['id'];?>' name='<?php echo $qestion['id'];?>'>
</div>
</div>
<br/>
<input type="button" id='next<?php echo $qestion['id'];?>' value='Next!' name='question' class='butt'/>
</div>
<?php }?>
</form>
Step 4:
now using jQuery i will show only one questions at a time.Here is jQuery script.
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/watch.js"></script>
<script>
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(document).ready(function(){
$('#demo1').stopwatch().stopwatch('start');
var steps = $('form').find(".questions");
var count = steps.size();
steps.each(function(i){
hider=i+2;
if (i == 0) {
$("#question_" + hider).hide();
createNextButton(i);
}
else if(count==i+1){
var step=i + 1;
//$("#next"+step).attr('type','submit');
$("#next"+step).on('click',function(){
submit();
});
}
else{
$("#question_" + hider).hide();
createNextButton(i);
}
});
function submit(){
$.ajax({
type: "POST",
url: "ajax.php",
dataType: 'json',
data: {
data: $('#quiz_form').serializeObject(),
type: 'results'
},
success: function(result) {
if (result && result.data) {
var r = result.data;
$("#quiz_form,#demo1").addClass("hide");
$('#result').show();
$('#right_answer').html(r.right_answer);
$('#wrong_answer').html(r.wrong_answer);
$('#unanswered').html(r.unanswered);
}
}
});
}
function createNextButton(i){
var step = i + 1;
var step1 = i + 2;
$('#next'+step).on('click',function(){
$("#question_" + step).hide();
$("#question_" + step1).show();
});
}
setTimeout(function() {
submit();
}, 50000);
$(document).on('click', '#retake_btn', function() {
$('#demo1').stopwatch().stopwatch('reset');
$("#quiz_form,#demo1").removeClass("hide");
$('#result').hide();
});
});
</script>
At the end final question I am posting all the answers to ajax.php file using ajax to validate right, wrong and unanswered questions.
$.ajax({
type: "POST",
url: "ajax.php",
dataType: 'json',
data: {
data: $('#quiz_form').serializeObject(),
type: 'results'
},
success: function(result) {
if (result && result.data) {
var r = result.data;
$("#quiz_form,#demo1").addClass("hide");
$('#result').show();
$('#right_answer').html(r.right_answer);
$('#wrong_answer').html(r.wrong_answer);
$('#unanswered').html(r.unanswered);
}
}
});
Step 5:
Finally create ajax.php and functions.php files. Where ajax.php receives ajax request, then it calls the getResults() function in functions.php file to validate your answers.
<?php
/**
* File: ajax.php
*
* @author: Muni
* @site: https://smarttutorials.net/
*/
require_once 'config.php';
require_once 'functions.php';
$data = $_POST;
try {
if (!empty($data) && !empty($data['type']) && !empty($data['data'])) {
api($data['type'], $data['data']);
} else {
sendResponse(0, "Invaild Request", []);
}
} catch (Exception $e) {
sendResponse(0, $e->getMessage(), []);
}
exit;
function api($type, $data)
{
switch ($type) {
case 'results':
$results = getResults($data);
sendResponse(1, "Quiz Results", $results);
break;
default:
# code...
break;
}
}
function sendResponse($status, $message, $data)
{
header('Content-Type: application/json');
if ($status) {
http_response_code(200);
$response = [
"code" => 200,
"message" => $message,
"data" => $data
];
echo json_encode($response);
} else {
http_response_code(500);
$response = [
"code" => 500,
"message" => $message,
"data" => $data
];
echo json_encode($response);
}
exit;
}
exit;
<?php
/**
* File: questions.php
*
* @author: Muni
* @site: https://smarttutorials.net/
*/
/**
* Get Questions
*/
function getQuestions()
{
global $mysqli;
$stmt = $mysqli->prepare("select * from questions");
if (!($stmt)) {
throw new Exception("Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error);
}
if (!$stmt->execute()) {
throw new Exception("Execute failed: (" . $stmt->errno . ") " . $stmt->error);
}
if (!($res = $stmt->get_result())) {
throw new Exception("Getting result set failed: (" . $stmt->errno . ") " . $stmt->error);
}
return $res->fetch_all(MYSQLI_ASSOC);
}
/**
* Get Results
*/
function getResults($postData)
{
$results = getQuestions();
$i=1;
$right_answer=0;
$wrong_answer=0;
$unanswered=0;
foreach ($results as $key => $result) {
$k = $key + 1;
if($result['answer']==$postData["$k"]){
$right_answer++;
}else if($postData["$k"]==5){
$unanswered++;
}
else{
$wrong_answer++;
}
$i++;
}
return [
"right_answer"=> $right_answer,
"wrong_answer"=> $wrong_answer,
"unanswered"=> $unanswered
];
}
Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts
If you want any of my script need to be customized according to your business requirement,
Please feel free to contact me [at] muni2explore[at]gmail.com
Note: But it will be charged based on your customization requirement