


How to use jQuery PHP MySQL to implement an online test project, jquerymysql_PHP tutorial
How to use jQuery PHP MySQL to implement an online test project, jquerymysql
In the previous article, we introduced the effect of test questions implemented using jQuery. Then this article will use examples to introduce how to use jQuery PHP MySQL to implement online test questions, including dynamic reading of questions, background scoring after answering the questions, and returning the answer results. This is a comprehensive WEB application article. It is recommended that you who read this article should have basic knowledge of HTML, jQuery, PHP and MySQL.
quiz.php
For the convenience of explanation here, I mixed php and HTML in the quiz.php file. First, it is the same as the previous article on this site: the test answering function implemented by jQuery. Load the jQuery library and quizs.js file, and then add the test question html structure at the appropriate location.
<div id="quiz-container"></div>
We need to read the question information when the page is loaded, and call jQuery to display it. The question information comes from the database. We can first add the question and its answer option information to the data table quiz.
We construct a SQL statement, use PHP to query the database, and read the question and answer option information. Note that we do not need to read the correct answer at this time. Then assign the question information to the variable $json in JSON format.
<?php include_once("connect.php");//连接数据库 $sql = "select * from quiz order by id asc"; $query = mysql_query($sql); //查询数据 while($row=mysql_fetch_array($query)){ $answers = explode('###',$row['answer']); //将答案选项分开 $arr[] = array( 'question' => $row['id'].'、'.$row['question'], //题目 'answers' => $answers //答案选项 ); } $json = json_encode($arr); //转换json格式 ?>
We got a string of data in json format, and then called jquizzy() as introduced in the previous article. The method is as follows:
$(function(){ $('#quiz-container').jquizzy({ questions: <?php echo $json;?>, //试题信息 sendResultsURL: 'data.php' //结果处理地址 }); });
In this way, let’s run the web page quiz.php again to see if a test question is generated. Looking at the source code, we can only see the json data, but not the answer part corresponding to the test question.
data.php
When calling the test question, there is an option sendResultsURL. When the user finishes typing the question and clicks the "Finish" button, an Ajax interactive request is sent to the background data.php. data.php will respond based on the user's answer. , compare the correct answers, and then give the user's score.
include_once("connect.php"); //连接数据库 $data = $_REQUEST['an']; //获取答题信息 $answers = explode('|',$data); //分析数据 $an_len = count($answers)-1; //题目数 $sql = "select correct from quiz order by id asc"; $query = mysql_query($sql); //查询表 $i = 0; $score = 0; //初始得分 $q_right = 0; //答对的题数 while($row=mysql_fetch_array($query)){ if($answers[$i]==$row['correct']){ //比对正确答案 $arr['res'][] = 1; //正确 $q_right += 1; //正确答题数+1 }else{ $arr['res'][] = 0; //错误 } $i++; } $arr['score'] = round(($q_right/$an_len)*100); //计算总得分 echo json_encode($arr);
In data.php, first connect to the database and receive the processing parameter an, which is the answer to the front-end user's question. Then query the data table, compare the answer submitted by the user with the correct answer to the question in the data table, and make corresponding decisions after comparison. Processing, and calculates the score obtained by the user's answer, and finally outputs and returns json format data to the front desk call.
quizs.js
We have modified the js code, mainly for the front and backend ajax interaction part. The core parts of quizs.js are as follows:
if (config.sendResultsURL !== null) { var collate = []; var myanswers = ''; //获取用户所答题的答案 for (r = 0; r < userAnswers.length; r++) { collate.push('{"questionNumber":"' + parseInt(r + 1, 10) + '", "userAnswer":"' + userAnswers[r] + '"}'); myanswers = myanswers + userAnswers[r]+'|'; } //Ajax交互 $.getJSON(config.sendResultsURL,{an:myanswers},function(json){ if(json==null){ alert('通讯失败!'); }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>'; }); resultSet = '<h2 id="judgeSkills-json-score-br-您的分数-json-score">' + judgeSkills(json.score) + '<br/> 您的分数: ' + json.score + '</h2><div class="jquizzy-clear"></div>' + resultSet + '<div class="jquizzy-clear"></div>'; superContainer.find('.result-keeper').html(resultSet).show(500); } }); }
After the user answers the question, the answer to the question answered by the user is formed into a string in the form of "1|2|4|1|3|", and then the answer is submitted to the parameter an through $.getJSON to the background, and the background PHP processing ratio After checking the correct answer, the comparison result is returned. The returned result is as follows: {"res":[1,0,1,1,0],"score":60}, res is the answer comparison result, indicating five values respectively. The answer result of a question, 1 means the answer is normal, 0 means the answer is wrong, and score means the score. Then the returned results are processed to obtain the evaluation results and total score of each question, and the corresponding html structure is generated.
MySQL
Finally, attach the structure of the mysql data table quiz:
CREATE TABLE IF NOT EXISTS `quiz` ( `id` int(11) NOT NULL AUTO_INCREMENT, `question` varchar(100) NOT NULL, `answer` varchar(500) NOT NULL, `correct` tinyint(2) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
You can add information to the table, or directly import the quiz.sql file in the source package.
The above is the entire content of this article, I hope you all like it.

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

The session ID should be regenerated regularly at login, before sensitive operations, and every 30 minutes. 1. Regenerate the session ID when logging in to prevent session fixed attacks. 2. Regenerate before sensitive operations to improve safety. 3. Regular regeneration reduces long-term utilization risks, but the user experience needs to be weighed.

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1
Easy-to-use and free code editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.