PHP页面刷新场景下测验计分系统的实现方案咨询
解决PHP测验页面刷新后计分丢失的问题
老兄,你遇到的问题本质是HTTP的无状态特性导致的——每次页面刷新,PHP脚本都会从头执行一遍,你定义的普通变量(比如计分计数器)会被重新初始化,之前的进度自然就丢了。要解决这个问题,我们需要用**Session(会话)**来持久化用户的计分和答题进度,Session数据会存在服务器端,只要用户的浏览器会话没结束,数据就会一直保留。
下面是具体的实现步骤和修改后的代码:
1. 启用Session(必须第一步)
在你的PHP脚本最最开头(任何HTML输出、空格甚至换行之前)加上session_start();,这是使用Session的前提:
<?php session_start(); // 必须放在最开头,不能有任何输出之前
2. 初始化Session里的计分和答题进度
第一次访问页面时,初始化计分和当前题目索引:
// 初始化Session变量(仅在第一次访问时) if (!isset($_SESSION['score'])) { $_SESSION['score'] = 0; } if (!isset($_SESSION['currentQuestion'])) { $_SESSION['currentQuestion'] = 0; } $questionsAndAnwsers = array( array("question" => " What early cartoon character created by the Disney Studio was Mickey Mouse based off of ?", "answer" => "Oswald The Lucky Rabbit"), array("question" => "Who invented the first TV ? Please use full name.", "answer" => "Philo Taylor Farnsworth"), array("question" => "When was Warner Brothers founded ? Format: Month Day, Year", "answer" => "April 4, 1923"), array("question" => "When was Superman's first appearance date ? Format: Month Year", "answer" => "June 1938"), array("question" => "What does the acronym OWN, for the cable television channel, stand for ?", "answer" => "Oprah Winfrey Network"), array("question" => "What type of dog is Scooby Doo from the cartoon series, Scooby Doo ?", "answer" => "Great Dane"), array("question" => "What type of food does Garfield the cat love ?", "answer" => "Lasagna"), array("question" => "How many Pokemon were in Generation I ? Use number not word.", "answer" => "151"), // 剩下的题目继续添加 );
3. 修改答题逻辑,更新Session中的计分和进度
把原来使用$currentQuestion的地方替换成$_SESSION['currentQuestion'],并根据答题对错更新分数:
// 处理用户提交的答案 if (isset($_POST["guess"])) { $currentQuestionIndex = $_SESSION['currentQuestion']; $currentAnswer = $questionsAndAnwsers[$currentQuestionIndex]["answer"]; $userGuess = $_POST["guess"]; // 判断是否答完所有题目(假设总共有16题,索引0-15) if ($currentQuestionIndex == 15) { // 这里可以跳转到结果页面,显示最终分数 header("Location: http://students.purchase.edu/martin.mcnicholas/scriptingfortheweb/index2.html"); exit(); } if ($userGuess == $currentAnswer) { // 答对:加分,跳转到下一题 $_SESSION['score'] += 1; // 你可以改成自定义分值,比如+5 $_SESSION['currentQuestion']++; // 输出答对提示 print ("<span class='Stylize2'>Your answer: $userGuess <br>"); print("The answer expected: $currentAnswer<br>"); print("Answer Correct! Current Score: {$_SESSION['score']}<br><br>"); // 显示对应图片 $images = [ 1 => 'MickeyMouse.png', 2 => 'Philo.jpg', // 更多图片对应关系 ]; if (array_key_exists($_SESSION['currentQuestion'], $images)) { echo "<img src='{$images[$_SESSION['currentQuestion']]}' alt='Question Image' height='200'><br><br>"; } else { echo "Image not found<br><br>"; } print("Next Question Below<br></span><br><br>"); } else { // 答错:可以选择扣分或者重置,这里按你原来的逻辑回到第0题,同时可以重置分数或者扣分 $_SESSION['score'] -= 1; // 比如答错扣1分,不想扣分就删掉这行 $_SESSION['currentQuestion'] = 0; // 输出答错提示 print ("<span class='Stylize'>Your answer: $userGuess <br>"); print("You have failed.. Current Score: {$_SESSION['score']}<br>"); echo '<img src=angry.gif height="200"></span><br><br>'; $test = '251993__kwahmah-02__distorted-voice-18.wav'; echo '<audio autoplay loop>'; echo "<source src='$test' type='audio/wav'>"; echo 'Your browser does not support the audio element'; echo '</audio>'; } } // 获取当前要显示的题目 $currentQuestion = $questionsAndAnwsers[$_SESSION['currentQuestion']]; ?> <!-- 显示题目和答题表单 --> <h3><?php echo $currentQuestion['question']; ?></h3> <form method="post"> <input type="text" name="guess" placeholder="Enter your answer"> <button type="submit">Submit Answer</button> </form>
关键注意事项
session_start()必须放在PHP脚本的最开头,不能有任何HTML输出、空格甚至换行,否则会报错。- 如果需要重置用户的计分和进度(比如添加一个重置按钮),可以用
session_destroy()或者直接重置Session变量:if (isset($_POST['reset'])) { $_SESSION['score'] = 0; $_SESSION['currentQuestion'] = 0; header("Location: {$_SERVER['PHP_SELF']}"); exit(); } - 测试时确保你的服务器支持Session(大部分主流PHP环境都默认支持)。
内容的提问来源于stack exchange,提问作者user9453652
相关产品推荐
相关产品推荐

