Jquery+php+mysql to implement an online exam function

Source: Internet
Author: User
Tags explode json php and php and mysql jquery library

In the previous article, we introduced the results of a test question implemented using jquery. Then this article will be combined with examples to introduce how to use Jquery+php+mysql to achieve online test questions, including dynamic reading topics, complete the background score, and return to answer the results. This is a comprehensive Web application article, it is recommended that you read this article you should have Html,jquery and PHP and MySQL and other basic knowledge.

quiz.php

Here I mix PHP and HTML in quiz.php files for easy explanation. First and this site on the article: jquery implementation of the test answer function, loaded into the jquery library and quizs.js files, and then in the appropriate place to add the test title HTML structure.

<div id= "Quiz-container" ></div>

We're going to read the topic information when the page loads and show it to the jquery call. The topic information comes from the database, we can add the topic and the answer option information in the datasheet quiz first.
We do this by constructing SQL statements, using PHP to query the database, reading questions and answer options, and noticing that we don't need to read the correct answers at this time. The topic information is then assigned to the variable $json in JSON format.

<?php

include_once ("connect.php"),//Connection database

$sql = "SELECT * from quiz ORDER by id ASC";

$query = mysql_query ($sql); Query data

while ($row =mysql_fetch_array ($query)) {

$answers = explode (' ### ', $row [' answer ']);//separate answer options

$  Arr[] = Array (

' question ' => $row [' id ']. ', '. $row [' question '],//title

' Answers ' => $answers Answer option

);

} 

$json = Json_encode ($arr); Convert JSON format

?>


We got a bunch of JSON-formatted data and then, like the one in the previous article, called Jquizzy () as follows:

$ (function () {

$ (' #quiz-container '). Jquizzy ({

questions: <?php echo $json;? ",///test information

sendresultsurl: ' data.php '//Result processing address

}";

});

In this way, we will run the page quiz.php, is not generated a test question, look at the source code, we can only see the JSON data, but can not see the answer part of the question.

data.php

In the call to test questions, there is an option Sendresultsurl, it is in the user hit the title, click the "Finish" button, to the background data.php send an AJAX interactive request, data.php will be based on the user's answer, compared to the correct answer, and then give the user scores.

Include_once ("connect.php");  //connection database     $data  = $_request[' an ']; //get the answer information   $ Answers = explode (' | ', $data)  //analysis data   $an _len = count ($answers) -1; //number of topics     $sql  =  "SELECT&NBSP;CORRECT&NBSP;FROM&NBSP;QUIZ&NBSP;ORDER&NBSP;BY&NBSP;ID&NBSP;ASC";   $query  = mysql_query ($sql)  //query table   $i  = 0;  $score  = 0;  Initial score   $q _right = 0; //correct number of questions   while ($row =mysql_fetch_array ($query)) {       if ($answers [$i]== $row [' correct ']) { //correct answer             $arr [' res '][] = 1; //correct            $q _right  += 1; //correct answer number +1      }else{            $arr [' res '][] = 0; //error       }       $i ++; }  $arr [' Score '] = round ($q _right/$an _len) *100) Calculation of total points   echo  json_encode ($arr);


In data.php, you first connect to the database, receive processing parameters An,an is the answer to the front-end users, and then query the data table, the user submitted the answer and the correct answer to the problem in the data table, compared to do the corresponding processing, and calculate the user answer scores, the final output returns JSON format data to the foreground call.

Quizs.js

We have modified the JS code, mainly for the front and back of the Ajax interactive part of the Quizs.js, the core part of the following:

if  (config.sendresultsurl !== null)  {      var collate =  [];      var myanswers =  ';      // Get answers to user questions       for  (r = 0; r < useranswers.length;  r++)  {          collate.push (' {"Questionnumber '):" '  + parseint (r + 1, 10)  +  ' ", " useranswer ":" '  + useranswers[r ] +  ' "}");          myanswers = myanswers  + useranswers[r]+ ' | ';

      }            //ajax Interactive       $.getjson (Config.sendresultsurl,{an:myanswers},function (JSON) {           if (json==null) {               alert (' Communication failed! ');          }else{                            var corects = json[' res '];               $.each (Corects,function (index,array) {                   resultSet +=  ' <div class= ' result-row ' > '  +   (corects[index] === 1 ?  "<div class= ' correct ' >#" + (index + 1) + " <span></span></div> ": " <div class= ' wrong ' ># "+ (index + 1) +" <span ></span></div> ") + ' </div> ';            &NBSP;&NBSP;&NBSP});              resultSet =  ' 

After the user answers the questions, the answer to the user is composed of strings such as "1|2|4|1|3|" The form, and then through the $.getjson the answer to the parameter an submit to the background, the background of PHP processing than the correct answer, will return to the results, return results such as: {"res": [1,0,1,1,0], "score": 60},res is the answer to the results, Respectively, the answer to the five questions, 1 of the answer is normal, 0 means that the answer error, score said score. Then the returned results are processed, the evaluation results and the total score of each question are obtained, and the corresponding HTML structure is generated.

Mysql

Finally, attach the structure of the MySQL datasheet quiz:

CREATE TABLE IF not EXISTS ' quiz ' (

' id ' int (one) not null auto_increment,

' question ' varchar (m) NOT NULL,

' answer ' varchar NOT NULL,

' correct ' tinyint (2) not NULL,

PRIMARY KEY (' id ')

engine=myisa M DEFAULT Charset=utf8;


You can add information to the table, or you can import the Quiz.sql file in the source package directly.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.