, , , ,

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…

59
quiz application using php,mysql,jquery, ajax, html5 and css3

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

 

 

quiz application using php,mysql,jquery, ajax, html5 and css3
Quiz Application using PHP, MySQL,jQuery, Ajax, html5 and css3

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
    ];
}

59 responses to “Quiz application Using PHP, jQuery, Ajax, MySQL and HTML5”

  1. Onyx

    Thanks for the nice tutorial.
    What modifications does it need to show questions in random order?

    Is an ORDER BY rand(); enough or needs more code added?

  2. vijay

    how can we create prev button functionality if i have to move back an forth before submitting

  3. isun

    hei..great tutorial…but why the result keeps appearing(more than one result)?how to stop it and make to give only one result?

  4. muni

    Hi Isun,

    Sorry for delay,
    Remove following lines of javascript

    setTimeout(function() {
    submit();
    }, 50000);
    it will solve your problems

  5. muni

    hi all,

    I added some of new features to this quiz application and posted in the following URL.
    Responsive Quiz Application Using PHP, MySQL, jQuery, Ajax and Twitter Bootstrap
    http://www.smarttutorials.net/responsive-quiz-application-using-php-mysql-jquery-ajax-and-twitter-bootstrap/

  6. Vitor Sousa

    Hi there, where are the .css file called style?

    And js??

    Thank you

  7. omar faruque

    hello muni. Thanks for your nice tutorial. I use your code in my page. But i face a new problem, I want to show a single question. But my all question are hide. plz want to know why?

    Thanks,
    I am weating for your response.
    Omar Faruque from Bangladesh.

  8. Narasinga Rao

    Sir, What changes should i make in watch.js, if i need to decrement my counter, i.e, i need to show countdown timer in quiz. Please help me out in this

  9. muni

    Hi Rao,

    Please refer following my tutorial you will get detailed info about timer usage.

    http://www.smarttutorials.net/responsive-quiz-application-using-php-mysql-jquery-ajax-and-twitter-bootstrap-part-2/

    Many Thanks,

    muni

  10. Narasinga Rao

    Thanks a lot muni,

    Another Problem is that, when i fetch questions from database, its displaying half a question. I mean, it is not displaying full question. Is there any restriction on displaying number of characters of question?

  11. Hi Rao,

    Please refer my latest tutorials on this quiz application, If you still have any problem let me know…

    http://www.smarttutorials.net/responsive-quiz-application-using-php-mysql-jquery-ajax-twitter-bootstrap-part-3/

    Many Thanks,

    muni

  12. khufu23

    Would it be a simple task to have the correct answer and an explanation displayed before jumping to the next question? Any ideas how to do that?

  13. Narasinga Rao

    Hi Muni, There is a problem in timer programming in version 2 and version 3 of your code, when we refresh the quiz page in browser the timer once again restarts from initial value. In Quiz that shouldn’t happen. Kindly provide me the answer for this. Accessing timestamp value to set it as session variable to avoid this problem.

  14. Keerthivasan

    I want source code bro urgently send me plz

  15. Jordan

    I’ve done the step by step process that you did in order to make the simple quiz application but my quiz application is displaying all the questions at the same time and I don’t know why. I need help getting it fixed. I’ve tried subscribing so that I can download the files directly but for some reason I can’t do that either. I just want to use the Quiz application Using PHP, jQuery, Ajax, MySQL and HTML5 Part-1 not part 2 or 3. Can you send the coding files directly to me? thank you.

  16. Swapnil

    Hey u jave given link to download but its not working so could u plz provide me the code for the above example

  17. Komal

    In your code is the no of questions are fixed because when I fetch the question from database and question is greater than 5 the page went broken. plz give me the solution

  18. eko

    i dont understand in file ajax.php, when $_POST[‘$i’] fill in. . ? in this statemen if($result[‘answer’]==$_POST[“$i”])

  19. Ginny

    Where can i download the .css and .js files??
    I need them asap… Please send the link,..i have subscribed also. when will i get the link?

  20. Rafael Diaz

    Hello, i suscribe for your page, but don’t have the code. Please, send me code, thanks!

  21. Hello Muni/Narasinga,

    Any answers to your question? I am facing thew same issue. Any help would be appreciated.

    Thanks & Regards,
    Textus Intentio

  22. if some one get the code please send me to my email add,[email protected]
    Thanks

  23. muni

    Sent

  24. dane

    please send me the complete source files

  25. muni

    sent 🙂

  26. Farooq

    here is a error in js

  27. Baljeet

    thanks a lot bro, really i am thankful to you, i become ur fan…

  28. Mehran

    Thank you very much for your help and your advices.

  29. Adheesh

    sir plz send me the complete source code please please asap 🙂

  30. Adheesh

    sir plz send me the complete source code please asap my email is [email protected]

  31. Dinesh

    Muni pls send the full source code for the quiz app to mail id [email protected] asap

  32. Rodrigo Macedo

    How to strip one time? or at least increases more? Why when the 50 seconds the quiz closes

  33. Rodrigo Macedo

    Stayed in this application server only modified the configuration in the database and does not return me the ajax.php

    http://quizprogrammer.hol.es/quiz/index.php

  34. Mech Clavano

    good morning sir! your tutorials are great. I subscribed already to get the source code but i didn’t receive. can you give me the source code??? this is the best quiz game i’m looking for. Im a student and part of our project is to make a quiz game. please help me.

    my email account — [email protected]

    Thank you! 🙂

  35. islam mrwan

    please sent me source files 🙂 thanks advanced
    my email : [email protected]

  36. Dao Yong

    please sent me the source files at [email protected] thanks

  37. payal

    please send me the code for quiz

  38. Dao Yong

    How do you create a back button and randomize and limit the questions. I need help. my email is [email protected]

  39. Rahul wadile

    How do you create a back button and randomize and limit the questions. I need help. my email is [email protected]

  40. Rahul wadile

    are u geting that code plase send me…this is my email Id: [email protected]

  41. Rahul wadile

    geting that code plase send me…this is my email Id: [email protected]

  42. abhishek raj

    Hello sir, I need source code of this quiz. Would you like to send me complete code at my email address?
    My email address is: [email protected]
    I have already subscribed here..
    Thanks in advance. 🙂

  43. Wellington Lopes

    Hello, I subscribed yesterday and asked for the .php file but I didn’t get it yet. Can you send it to me?

    If you can send the .js and .css I’d be glad too. Thanks.

  44. vivek

    send me php js and css file as early as possible plzz..id- [email protected]

  45. Ramkumar Boopathi

    Please provide this example with ‘Back’ button to go to previous question..

  46. Rocky Manalu

    dane,, Muni,, Please send me complete source file, thank you
    [email protected]

  47. Rocky Manalu

    please help me, i want this project
    send me in [email protected].

    thank you

  48. Sumanth Dg

    please send me a source file of above example to [email protected]

  49. Mirsaid

    ????

  50. Mirsaid

    Send it to me pleace

  51. Jitendra

    Sir
    Plz send me source code of quiz app.
    My email id
    [email protected]

  52. Durai

    Hi,

    Can you plz send me the .js and .css file.

  53. Durai

    Hi,

    Plz send me the code for quiz.
    I subscribed my mail id but not yet receive any mail.
    My Mail id is [email protected]

  54. shanaya bhatt

    please send me code sir and with mysqli if possible 🙂
    [email protected]

  55. sai kumar

    I subscribed with my mail id but not yet receive any download link.
    please send me the code to email [email protected]

Leave a Reply