Responsive Quiz application using PHP,Mysql,Bootstrap framework


In this tutorial we gonna learn about how to create a Responsive Quiz application using 
PHP, Mysql, and bootstrap. And this application also requires a Jquery plug-in's. 

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.
I hope all you installed the servers who run the PHP ,Mysql as a database. If you are not installed any server i strongly recommend to install xampp server on your PC.
Responsive Quiz Application Using PHP, MySQL, jQuery, Ajax and Twitter Bootstrap
Step 1: Create following three tables
1. users
2. categories
3. questions
Use following code to create tables in mysql DB
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`)
) 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`)
) 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`)
) AUTO_INCREMENT=21 ;
INSERT INTO `categories` (`id`, `category_name`) VALUES
(1, 'Sports'),
(2, 'HTML'),
(3, 'PHP'),
(4, 'CSS');
Using above sql code we can create table in the databases. Enter some sample data into the 'categories ' table like above.
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://trysorcecode.blogspot.in">Smart Tutorials</a>', '<a>http://trysorcecode.blogspot.in</a>', '<a url="http://smarttutorials.net">The Source Code</a>', '<a href="http://smarttutorials.net">The Sorce Code</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);
Step 2:
Create config.php file to keep database connection in a separate file. This file used to connect to database by using following connection strings. If you fail to connect to the database it will through an error to the user.
<?php
/*
 * Site : http:trysourcecode.blogspot.in
 */

define('BASE_PATH','http://localhost/new_quiz/');
define('DB_HOST', 'localhost');
define('DB_NAME', 'quiz');
define('DB_USER','root');
define('DB_PASSWORD','');

$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());

?>
Step 3:
Create index.php file and the following scripts in it, which take care user registration process.
<?php
session_start();
?>
<!---
Site : http:www.trysourcecode.blogspot.in
--->

<?php
require 'config.php';
?>
<!DOCTYPE html>
<html>
 <head>
  <title>Responsive Quiz Application Using PHP, MySQL, jQuery and Twitter Bootstrap</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- Bootstrap -->
  <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
  <link href="css/style.css" rel="stylesheet" media="screen">
  <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!--[if lt IE 9]>
  <script src="../../assets/js/html5shiv.js"></script>
  <script src="../../assets/js/respond.min.js"></script>
  <![endif]-->

 </head>
 <body>
  <header>
   <p class="text-center">
    Welcome <?php if(!empty($_SESSION['name'])){echo $_SESSION['name'];}?>
   </p>
  </header>
  <div class="container">
   <div class="row">
    <div class="col-xs-14 col-sm-7 col-lg-7">
     <div class='image'>
      <img src="image/logo.png" class="img-responsive"/>
     </div>
    </div>
    <div class="col-xs-10 col-sm-5 col-lg-5">
     <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">
        Kiss Me!!!
       </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">
                                Kiss Me!!!
                            </button>
                        </form>
      <?php }?>
     </div>
    </div>
   </div>
  </div>
  <footer>
   <p class="text-center" id="foot">
    &copy; <a href="http://trysourcecode.blogspot.in/" target="_blank">The Source Code </a>2013
   </p>
  </footer>
  <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
  <script src="js/jquery-1.10.2.min.js"></script>
  <script src="js/bootstrap.min.js"></script>

  <!-- Include all compiled plugins (below), or include individual files as needed -->
  <script src="js/jquery.validate.min.js"></script>

  <script>
   $(document).ready(function() {
    $("#signin").validate({
     submitHandler : function() {
         console.log(form.valid());
      if (form.valid()) {
          alert("sf");
       return true;
      } else {
       return false;
      }

     },
     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 : "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');
     }
    });
   });
  </script>

 </body>
</html>
Step4:
Now create check_name.php file which take care unique name check in the database while user registring.
<?php
/*
 * Site : http:www.trysourcecode.blogspot.com
 */
 require_once 'config.php';

 if(!empty($_POST['name'])){
     $name=$_POST['name'];
     $res=mysql_query("select count(user_name) as count from users where user_name='$name'") or die(mysql_error()); 
     $count=mysql_fetch_array($res);
     if($count[0]==0){
         echo 'true';
     }else{
         echo 'false';
     }
 }
?>
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
session_start();
?>
<!---
Site : http:www.trysourcecode.blogspot.com
--->

<?php 
require 'config.php';
$category='';
 if(!empty($_POST['name'])){
     $name=$_POST['name'];
     $category=$_POST['category'];
     mysql_query("INSERT INTO users (id, user_name,score,category_id)VALUES ('NULL','$name',0,'$category')") or die(mysql_error());
     $_SESSION['name']= $name;
     $_SESSION['id'] = mysql_insert_id();
 }
$category=$_POST['category'];
if(!empty($_SESSION['name'])){
?>
<!DOCTYPE html>
<html>
 <head>
  <title>Responsive Quiz Application Using PHP, MySQL, jQuery, Ajax and Twitter Bootstrap</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- Bootstrap -->
  <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
  <link href="css/style.css" rel="stylesheet" media="screen">

  <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!--[if lt IE 9]>
  <script src="../../assets/js/html5shiv.js"></script>
  <script src="../../assets/js/respond.min.js"></script>
  <![endif]-->
  <style>
   .container {
    margin-top: 110px;
   }
   .error {
    color: #B94A48;
   }
   .form-horizontal {
    margin-bottom: 0px;
   }
   .hide{display: none;}
  </style>
 </head>
 <body>
     <header>
            <p class="text-center">
                Welcome : <?php if(!empty($_SESSION['name'])){echo $_SESSION['name'];}?>
            </p>
        </header>

  <div class="container question">
   <div class="col-xs-12 col-sm-8 col-md-8 col-xs-offset-4 col-sm-offset-3 col-md-offset-3">
    <p>
     Responsive Quiz Application Using PHP, MySQL, jQuery, Ajax and Twitter Bootstrap
    </p>
    <hr>
    <form class="form-horizontal" role="form" id='login' method="post" action="result.php">
     <?php 
     $res = mysql_query("select * from questions where category_id='$category' ORDER BY RAND()") or die(mysql_error());
                    $rows = mysql_num_rows($res);
     $i=1;
                while($result=mysql_fetch_array($res)){?>

                    <?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>
                    <input type="radio" value="1" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/><?php echo $result['answer1'];?>
                   <br/>
                    <input type="radio" value="2" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/><?php echo $result['answer2'];?>
                    <br/>
                    <input type="radio" value="3" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/><?php echo $result['answer3'];?>
                    <br/>
                    <input type="radio" value="4" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/><?php echo $result['answer4'];?>
                    <br/>
                    <input type="radio" checked='checked' style='display:none' value="5" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/>                                                                      
                    <br/>
                    <button id='next<?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>
                    <input type="radio" value="1" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/><?php echo $result['answer1'];?>
                    <br/>
                    <input type="radio" value="2" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/><?php echo $result['answer2'];?>
                    <br/>
                    <input type="radio" value="3" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/><?php echo $result['answer3'];?>
                    <br/>
                    <input type="radio" value="4" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/><?php echo $result['answer4'];?>
                    <br/>
                    <input type="radio" checked='checked' style='display:none' value="5" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/>                                                                      
                    <br/>
                    <button id='pre<?php echo $i;?>' class='previous btn btn-success' type='button'>Previous</button>                    
                    <button id='next<?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>
                    <input type="radio" value="1" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/><?php echo $result['answer1'];?>
                    <br/>
                    <input type="radio" value="2" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/><?php echo $result['answer2'];?>
                    <br/>
                    <input type="radio" value="3" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/><?php echo $result['answer3'];?>
                    <br/>
                    <input type="radio" value="4" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/><?php echo $result['answer4'];?>
                    <br/>
                    <input type="radio" checked='checked' style='display:none' value="5" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/>                                                                      
                    <br/>

                    <button id='pre<?php echo $i;?>' class='previous btn btn-success' type='button'>Previous</button>                    
                    <button id='next<?php echo $i;?>' class='next btn btn-success' type='submit'>Finish</button>
                    </div>
     <?php } $i++;} ?>

    </form>
   </div>
  </div>
       <footer>
            <p class="text-center" id="foot">
                &copy; <a href="http://trysourcecode.blogspot.in/" target="_blank">The Sorce Code </a>2013
            </p>
        </footer>

<?php

if(isset($_POST[1])){ 
   $keys=array_keys($_POST);
   $order=join(",",$keys);

   //$query="select * from questions id IN($order) ORDER BY FIELD(id,$order)";
  // echo $query;exit;

   $response=mysql_query("select id,answer from questions where id IN($order) ORDER BY FIELD(id,$order)")   or die(mysql_error());
   $right_answer=0;
   $wrong_answer=0;
   $unanswered=0;
   while($result=mysql_fetch_array($response)){
       if($result['answer']==$_POST[$result['id']]){
               $right_answer++;
           }else if($_POST[$result['id']]==5){
               $unanswered++;
           }
           else{
               $wrong_answer++;
           }

   }

   echo "right_answer : ". $right_answer."<br>";
   echo "wrong_answer : ". $wrong_answer."<br>";
   echo "unanswered : ". $unanswered."<br>";
}
?>
  <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
  <script src="js/jquery-1.10.2.min.js"></script>
  <!-- Include all compiled plugins (below), or include individual files as needed -->
  <script src="js/bootstrap.min.js"></script>
  <script src="js/jquery.validate.min.js"></script>

  <script>
  $('.cont').addClass('hide');
  count=$('.questions').length;
   $('#question'+1).removeClass('hide');

   $(document).on('click','.next',function(){
       element=$(this).attr('id');
       last = parseInt(element.substr(element.length - 1));
       nex=last+1;
       $('#question'+last).addClass('hide');

       $('#question'+nex).removeClass('hide');
   });

   $(document).on('click','.previous',function(){
             element=$(this).attr('id');
             last = parseInt(element.substr(element.length - 1));
             pre=last-1;
             $('#question'+last).addClass('hide');

             $('#question'+pre).removeClass('hide');
         });

  </script>
 </body>
</html>
<?php }else{

 header( 'Location: http://localhost/new_quiz/index.php' ) ;

}
?>
Step 6:
Finally create result.php file and add the following lines of script in it.
<?php
session_start();
?>
<?php 
require 'config.php';
if(!empty($_SESSION['name'])){

    $right_answer=0;
    $wrong_answer=0;
    $unanswered=0; 

   $keys=array_keys($_POST);
   $order=join(",",$keys);

   //$query="select * from questions id IN($order) ORDER BY FIELD(id,$order)";
  // echo $query;exit;

   $response=mysql_query("select id,answer from questions where id IN($order) ORDER BY FIELD(id,$order)")   or die(mysql_error());

   while($result=mysql_fetch_array($response)){
       if($result['answer']==$_POST[$result['id']]){
               $right_answer++;
           }else if($_POST[$result['id']]==5){
               $unanswered++;
           }
           else{
               $wrong_answer++;
           }
   }
   $name=$_SESSION['name'];  
   mysql_query("update users set score='$right_answer' where user_name='$name'");
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Responsive Quiz Application Using PHP, MySQL, jQuery, Ajax and Twitter Bootstrap</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <!-- Bootstrap -->
        <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
        <link href="css/style.css" rel="stylesheet" media="screen">
        <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
        <!--[if lt IE 9]>
        <script src="../../assets/js/html5shiv.js"></script>
        <script src="../../assets/js/respond.min.js"></script>
        <![endif]-->

    </head>
    <body>
        <header>
            <p class="text-center">
                Welcome <?php 
                if(!empty($_SESSION['name'])){
                    echo $_SESSION['name'];
                }?>

            </p>
        </header>
        <div class="container result">
            <div class="row"> 
                    <div class='result-logo'>
                            <img src="image/Quiz_result.png" class="img-responsive"/>
                    </div>    
           </div>  
           <hr>   
           <div class="row"> 
                  <div class="col-xs-18 col-sm-9 col-lg-9"> 
                    <div class='result-logo1'>
                            <img src="image/cat.GIF" class="img-responsive"/>
                    </div>
                  </div>

                  <div class="col-xs-6 col-sm-3 col-lg-3"> 
                     <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 style="margin-top: 30%">
                        <p>Total no. of right answers : <span class="answer"><?php echo $right_answer;?></span></p>
                        <p>Total no. of wrong answers : <span class="answer"><?php echo $wrong_answer;?></span></p>
                        <p>Total no. of Unanswered Questions : <span class="answer"><?php echo $unanswered;?></span></p>                   
                       </div> 

                   </div>

            </div>    
            <div class="row">    

            </div>
        </div>
        <footer>
            <p class="text-center" id="foot">
                &copy; <a href="http://trysourcecode.blogspot.in/" target="_blank">The Sorce Code</a>2013
            </p>
        </footer>
        <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
        <script src="js/jquery-1.10.2.min.js"></script>
        <script src="js/bootstrap.min.js"></script>

        <!-- Include all compiled plugins (below), or include individual files as needed -->
        <script src="js/jquery.validate.min.js"></script>

    </body>
</html>
<?php }else{

 header( 'Location: http://localhost/new_quiz/index.php' ) ;

}?>
Step 7:
Finally create logout.php file which take care user logout process as well it redirects the user to index page.It will destroy the session.
<?php
session_start();
session_destroy();
header( 'Location: http://localhost/new_quiz/index.php' ) ;
?>

0 comments :

Post a Comment