Responsive Quiz Application Using PHP, MySQL, jQuery, Ajax and Twitter Bootstrap
In this tutorial i had some of new features to the quiz application comparing previous one (Quiz application Using PHP, jQuery, Ajax, MySQL and HTML5). Following features are added
Note : You can refer my latest Quiz application
Responsive PHP Quiz Script
1. This Quiz application is responsive one, it will automatically render in desktop, mobile and tablet based on screen size and resolution.
2. This application has both previous and next button functionality.
3. For demo purpose I added user simple user registration.
4. User can choose category when they going to start an Quiz application.
5. Finally user score will be saved in database.
Note: Once you completed this tutorial. Please refer latest versions of the quiz application
Responsive Quiz Application Using PHP, MySQL, jQuery, Ajax and Twitter Bootstrap part-2
Responsive Quiz Application Using PHP, MySQL, jQuery, Ajax and Twitter Bootstrap Part-3
This is very simple application, please follow the this tutorial at the end you can make it yourself.
Step 1: Create following three tables
1. users
2. categories
3. questions
using following sql queries.
CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_name` varchar(50) NOT NULL, `score` int(11) NOT NULL, `category_id` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
CREATE TABLE IF NOT EXISTS `categories` ( `id` int(11) NOT NULL AUTO_INCREMENT, `category_name` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
CREATE TABLE IF NOT EXISTS `questions` ( `id` int(11) NOT NULL AUTO_INCREMENT, `question_name` text NOT NULL, `answer1` varchar(250) NOT NULL, `answer2` varchar(250) NOT NULL, `answer3` varchar(250) NOT NULL, `answer4` varchar(250) NOT NULL, `answer` varchar(250) NOT NULL, `category_id` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=21 ;
Now add the following sample data’s in it.
INSERT INTO `categories` (`id`, `category_name`) VALUES (1, 'Sports'), (2, 'HTML'), (3, 'PHP'), (4, 'CSS');
INSERT INTO `questions` (`id`, `question_name`, `answer1`, `answer2`, `answer3`, `answer4`, `answer`, `category_id`) VALUES (1, 'Where did India play its 1st one day international match?', 'Lords', 'Headingley', 'Taunton', 'The Oval', '2', 1), (2, 'Who was the 1st ODI captain for India?\r\n', 'Ajit Wadekar ', 'Bishen Singh Bedi', 'Nawab Pataudi', 'Vinoo Mankad ', '1', 1), (3, 'Who has made the Fastest Test century in Test Cricket ?\r\n\r\n\r\n\r\n', 'Sachin Tendulkar', ' Sahid Afridi', ' Virender Sehwag', 'Vivian Richards', '4', 1), (4, 'Which Bowler had the Best figures in a Test Match ?\r\n\r\n\r\n\r\n\r\n', 'Muttiah Muralitharan', 'Bob Massie', 'Jim Laker', 'George Lohmann', '3', 1), (5, 'Which team has the Largest successful run chase record in ODIs ?\r\n\r\n\r\n\r\n\r\n', 'England', 'South Africa', 'Australia', 'India', '2', 1), (6, 'What does HTML stand for?\r\n\r\n \r\n \r\n ', 'Hyper Text Markup Language', 'Hyperlinks and Text Markup Language', 'Home Tool Markup Language', 'Highly Text Markup Language', '1', 2), (7, 'Who is making the Web standards?\r\n\r\n \r\n \r\n \r\n \r\n', 'Microsoft', 'Google', 'The World Wide Web Consortium', 'Mozilla', '3', 2), (8, 'What is the correct HTML for creating a hyperlink?\r\n\r\n \r\n \r\n \r\n ', '<a name="http://smarttutorials.net">Smart Tutorials</a>', '<a>http://smarttutorials.net</a>', '<a url="http://smarttutorials.net">Smart Tutorials</a>', '<a href="http://smarttutorials.net">Smart Tutorials</a>', '4', 2), (9, 'What is the HTML element to bold a text?\r\n\r\n\r\n\r\n\r\n', '<b>', '<bold>', '<wide>', '<big>', '1', 2), (10, 'What is the HTML tag for a link?\r\n\r\n\r\n\r\n\r\n', '<link>', '<ref>', '<a>', '<hper>', '3', 2), (11, 'What does CSS stand for?\r\n\r\n \r\n \r\n \r\n ', 'Creative Style Sheets', 'Colorful Style Sheets', 'Computer Style Sheets', 'Cascading Style Sheets', '4', 4), (12, 'Where in an HTML document is the correct place to refer to an external style sheet?\r\n\r\n \r\n \r\n \r\n ', 'In the <body> section ', 'At the end of the document', 'At the top of the document', 'In the <head> section ', '4', 4), (13, 'Which HTML tag is used to define an internal style sheet?\r\n\r\n \r\n \r\n ', '<script>', '<css>', '<style>', '<link>', '3', 4), (14, 'Which is the correct CSS syntax?\r\n\r\n \r\n \r\n \r\n ', 'body:color=black;', '{body;color:black;}', 'body {color: black;}', '{body:color=black;}', '3', 4), (15, 'Which property is used to change the background color?\r\n\r\n \r\n \r\n ', 'background-color', 'color', 'bgcolor', 'bg-color', '1', 4), (16, 'What does PHP stand for?\r\n\r\n \r\n \r\n ', ' PHP: Hypertext Preprocessor', 'Personal Hypertext Processor', 'Personal Home Page', 'Private Home Page', '1', 3), (17, 'PHP server scripts are surrounded by delimiters, which?\r\n\r\n \r\n \r\n \r\n ', '<?php>...</?>', '<?php ... ?>', '<script>...</script>', '<&>...</&>', '2', 3), (18, 'How do you write "Hello World" in PHP\r\n\r\n \r\n \r\n ', '"Hello World"', 'echo "Hello World"', 'Document.Write("Hello World");', 'print_f("Hello World");', '2', 3), (19, ' Which of the following is the way to create comments in PHP?\r\n\r\n\r\n \r\n \r\n ', '// commented code to end of line', '/* commented code here */', '# commented code to end of line', 'all of the above - correct', '4', 3), (20, 'What is the correct way to end a PHP statement?\r\n\r\n \r\n \r\n \r\n ', '</php>', '.', ';', 'New line', '3', 3);
Here is the sample database relational daigram of above three tables.
Step 2:
Create config.php file to keep database connection in a separte file. Also kept two utilities database related functions to prepare prepared statements and get results.
<?php
/**
* File: config.php
*
* @author: Muni
* @site: https://smarttutorials.net/
*/
session_start();
define('BASE_PATH','http://localhost/demo_tut/nquiz/');
define('DB_HOST', 'localhost');
define('DB_NAME', 'smarttut_demo');
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();
}
/**
* Preparing Statement
*/
function prepareStatement($sql, $params = null)
{
global $mysqli;
$stmt = $mysqli->prepare($sql);
if (!($stmt)) {
throw new Exception("Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error);
}
if (!empty($params) && is_array($params)) {
$count = count($params);
$bindStr = str_repeat('s', $count);
$stmt->bind_param($bindStr, ...$params);
}
if (!$stmt->execute()) {
throw new Exception("Execute failed: (" . $stmt->errno . ") " . $stmt->error);
}
return $stmt;
}
/**
* GetResult
*/
function getResult($stmt)
{
if (!($res = $stmt->get_result())) {
throw new Exception("Getting result set failed: (" . $stmt->errno . ") " . $stmt->error);
}
return $res;
}
Step 3:
Create index.php file and the following scripts in it, which take care user registration process.
<?php
/**
* File: index.php
*
* @author: Muni
* @site: https://smarttutorials.net/
*/
require 'config.php';
?>
<?php include_once 'templates/header.php' ?>
<div class="container vh-center">
<div class='image'>
<img src="image/logo.png" class="img-responsive"/>
</div>
<div class="intro">
<p class="text-center">
Please enter your name
</p>
<?php if (empty($_SESSION['name'])){ ?>
<form class="form-signin" method="post" id='signin' name="signin" action="questions.php">
<div class="form-group">
<input type="text" id='name' name='name' class="form-control" placeholder="Enter your Name"/>
<span class="help-block"></span>
</div>
<div class="form-group">
<select class="form-control" name="category" id="category">
<option value="">Choose your category</option>
<option value="1">Sports</option>
<option value="2">HTML</option>
<option value="3">PHP</option>
<option value="4">CSS</option>
</select>
<span class="help-block"></span>
</div>
<br>
<button class="btn btn-success btn-block" type="submit">
Start Quiz!!!
</button>
</form>
<?php }else{ ?>
<form class="form-signin" method="post" id='signin' name="signin" action="questions.php">
<div class="form-group">
<select class="form-control" name="category" id="category">
<option value="">Choose your category</option>
<option value="1">Sports</option>
<option value="2">HTML</option>
<option value="3">PHP</option>
<option value="4">CSS</option>
</select>
<span class="help-block"></span>
</div>
<br>
<button class="btn btn-success btn-block" type="submit">
Start Quiz!!!
</button>
</form>
<?php }?>
</div>
</div>
<?php include_once 'templates/footer.php' ?>
<script src="js/jquery-1.10.2.min.js"></script>
<script src='//cdn.jsdelivr.net/npm/jquery-validation@1.19.1/dist/jquery.validate.min.js'></script>
<script src="js/app.js"></script>
</body>
</html>
Step 4:
Now create check_name.php file which take care unique name check in the database while user registering.
<?php
/**
* File: check_name.php
*
* @author: Muni
* @site: https://smarttutorials.net/
*/
require_once 'config.php';
require_once 'functions.php';
if (isset($_POST['name']) && !empty($_POST['name'])) {
$count = checkName($_POST['name']);
if ($count == 0 ) {
echo 'true';
}else{
echo 'false';
}
} else {
echo 'false';
}
exit;
Step 5:
Now create question.php and add following scripts. This is main file of this quiz application which gets questions randomily from database for each the user. As well it take care previous and next button functionality using jQuery.
<?php
/**
* File: questions.php
*
* @author: Muni
* @site: https://smarttutorials.net/
*/
require_once 'config.php';
require_once 'functions.php';
try {
$category = '';
if (!empty($_POST['name'])) {
insertUserSelectedCategory($_POST);
}
$category = $_POST['category'];
if (empty($_SESSION['name'])) {
header('Location: index.php');
}
$questions = getQuestions($category);
$rows = count($questions);
} catch (Exception $e) {
//echo '<pre>';print_r($e);echo '</pre>';exit;
}
?>
<?php include_once 'templates/header.php' ?>
<div class="container question vh-center">
<div class="question-container">
<form class="form-horizontal" role="form" id='login' method="post" action="result.php">
<?php
$i=1;
foreach ($questions as $key => $result) {
?>
<?php if($i==1){?>
<div id='question<?php echo $i;?>' class='cont'>
<p class='questions' id="qname<?php echo $i;?>"> <?php echo $i?>.<?php echo $result['question_name'];?></p>
<hr>
<div class="form-group">
<input type="radio" value="1" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/>
<label for='radio1_<?php echo $result['id'];?>'><?php echo $result['answer1'];?></label>
</div>
<div class="form-group">
<input type="radio" value="2" id='radio2_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/>
<label for='radio2_<?php echo $result['id'];?>'><?php echo $result['answer2'];?></label>
</div>
<div class="form-group">
<input type="radio" value="3" id='radio3_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/>
<label for='radio3_<?php echo $result['id'];?>'><?php echo $result['answer3'];?></label>
</div>
<div class="form-group">
<input type="radio" value="4" id='radio4_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/>
<label for='radio4_<?php echo $result['id'];?>'><?php echo $result['answer4'];?></label>
</div>
<div class="form-group">
<input type="radio" checked='checked' style='display:none' value="5" id='radio5_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/>
</div>
<button id='<?php echo $i;?>' class='next btn btn-success' type='button'>Next</button>
</div>
<?php } elseif($i<1 || $i<$rows) { ?>
<div id='question<?php echo $i;?>' class='cont'>
<p class='questions' id="qname<?php echo $i;?>"><?php echo $i?>.<?php echo $result['question_name'];?></p>
<div class="form-group">
<input type="radio" value="1" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/>
<label for='radio1_<?php echo $result['id'];?>'><?php echo $result['answer1'];?></label>
</div>
<div class="form-group">
<input type="radio" value="2" id='radio2_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/>
<label for='radio2_<?php echo $result['id'];?>'><?php echo $result['answer2'];?></label>
</div>
<div class="form-group">
<input type="radio" value="3" id='radio3_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/>
<label for='radio3_<?php echo $result['id'];?>'><?php echo $result['answer3'];?></label>
</div>
<div class="form-group">
<input type="radio" value="4" id='radio4_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/>
<label for='radio4_<?php echo $result['id'];?>'><?php echo $result['answer4'];?></label>
</div>
<div class="form-group">
<input type="radio" checked='checked' style='display:none' value="5" id='radio5_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/>
</div>
<button id='<?php echo $i;?>' class='previous btn btn-success' type='button'>Previous</button>
<button id='<?php echo $i;?>' class='next btn btn-success' type='button' >Next</button>
</div>
<?php } elseif($i==$rows) { ?>
<div id='question<?php echo $i;?>' class='cont'>
<p class='questions' id="qname<?php echo $i;?>"><?php echo $i?>.<?php echo $result['question_name'];?></p>
<div class="form-group">
<input type="radio" value="1" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/>
<label for='radio1_<?php echo $result['id'];?>'><?php echo $result['answer1'];?></label>
</div>
<div class="form-group">
<input type="radio" value="2" id='radio2_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/>
<label for='radio2_<?php echo $result['id'];?>'><?php echo $result['answer2'];?></label>
</div>
<div class="form-group">
<input type="radio" value="3" id='radio3_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/>
<label for='radio3_<?php echo $result['id'];?>'><?php echo $result['answer3'];?></label>
</div>
<div class="form-group">
<input type="radio" value="4" id='radio4_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/>
<label for='radio4_<?php echo $result['id'];?>'><?php echo $result['answer4'];?></label>
</div>
<div class="form-group">
<input type="radio" checked='checked' style='display:none' value="5" id='radio5_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/>
</div>
<button id='<?php echo $i;?>' class='previous btn btn-success' type='button'>Previous</button>
<button id='<?php echo $i;?>' class='next btn btn-success' type='submit'>Finish</button>
</div>
<?php } $i++;} ?>
</form>
</div>
</div>
<?php include_once 'templates/footer.php' ?>
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
Step 6:
Finally create result.php file and add the following lines of script in it.
<?php
require_once 'config.php';
require_once 'functions.php';
if (empty($_SESSION['name'])) {
header( 'Location: index.php') ;exit;
}
if (!empty($_POST)) {
$keys = array_keys( $_POST );
$order = join(",", $keys );
$results = getAnswers($order);
updateAnsers($results['right_answer'], $_SESSION['name']);
}
?>
<?php include_once 'templates/header.php' ?>
<div class="container result vh-center">
<div class="w100">
<div class="row">
<div class='result-logo'>
<img src="image/Quiz_result.png" class="img-responsive"/>
</div>
</div>
<hr>
<div class="row dflex results-container">
<div class='text-center left'>
<img src="image/cat.GIF" class="img-responsive"/>
</div>
<div class="results right">
<a href="<?php echo BASE_PATH;?>" class='btn btn-success'>Start new Quiz!!!</a>
<a href="<?php echo BASE_PATH.'logout.php';?>" class='btn btn-success'>Logout</a>
<div>
<p class="mtb-1">Total no. of right answers : <span class="answer"><?php echo $results['right_answer'];?></span></p>
<p class="mtb-1">Total no. of wrong answers : <span class="answer"><?php echo $results['wrong_answer'];?></span></p>
<p class="mtb-1">Total no. of Unanswered Questions : <span class="answer"><?php echo $results['unanswered'];?></span></p>
</div>
</div>
</div>
</div>
</div>
<?php include_once 'templates/footer.php' ?>
</body>
</html>
Step 7:
Next create logout.php file which take care user logout process as well it redirects the user to index page.
<?php
session_start();
session_destroy();
require 'config.php';
header( 'Location: '.BASE_PATH ) ;
Step 8:
Finally create app.js file, then keep the user validation logic during user registration & Quiz questions pagination logic (previous & next button logic).
$(document).ready(function() {
if ($("#signin").validate) {
$("#signin").validate({
submitHandler: function(form) {
form.submit();
},
rules : {
name : {
required : true,
minlength : 3,
remote : {
url : "check_name.php",
type : "post",
data : {
username : function() {
return $("#name").val();
}
}
}
},
category:{
required : true
}
},
messages : {
name : {
required : "Please enter your name",
remote : function(){
$('#name').rules('remove', 'remote');
return "";
return "Name is already taken, Please choose some other name"
}
},
category:{
required : "Please choose your category to start Quiz"
}
},
errorPlacement : function(error, element) {
$(element).closest('.form-group').find('.help-block').html(error.html());
},
highlight : function(element) {
$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
},
success : function(element, lab) {
var messages = new Array("That's Great!", "Looks good!", "You got it!", "Great Job!", "Smart!", "That's it!");
var num = Math.floor(Math.random() * 6);
$(lab).closest('.form-group').find('.help-block').text(messages[num]);
$(lab).addClass('valid').closest('.form-group').removeClass('has-error').addClass('has-success');
}
});
}
});
$('.cont').addClass('hide');
count = $('.questions').length;
$('#question'+1).removeClass('hide');
$(document).on('click','.next',function(){
last=parseInt($(this).attr('id'));
nex = last+1;
$('#question'+last).addClass('hide');
$('#question'+nex).removeClass('hide');
});
$(document).on('click','.previous',function(){
last=parseInt($(this).attr('id'));
pre = last-1;
$('#question'+last).addClass('hide');
$('#question'+pre).removeClass('hide');
});
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