php 选择题如何实现
PHP 选择题实现方法
使用 PHP 实现选择题功能通常涉及前端展示、后端处理和数据库存储。以下是常见的实现方式:
基础表单实现
创建 HTML 表单提交选择题答案:
<form method="post" action="process_quiz.php">
<p>1. PHP 是什么的缩写?</p>
<input type="radio" name="q1" value="A"> A: Personal Home Page<br>
<input type="radio" name="q1" value="B"> B: Preprocessor Hypertext Page<br>
<input type="radio" name="q1" value="C"> C: Hypertext Preprocessor<br>
<input type="submit" value="提交答案">
</form>
处理提交的答案
在 process_quiz.php 中处理用户选择:

$correct_answers = [
'q1' => 'C'
];
$user_answer = $_POST['q1'];
if ($user_answer == $correct_answers['q1']) {
echo "回答正确!";
} else {
echo "回答错误,正确答案是 ".$correct_answers['q1'];
}
数据库存储题目
使用数据库存储选择题:
// 数据库连接
$db = new PDO('mysql:host=localhost;dbname=quiz', 'username', 'password');
// 获取题目
$stmt = $db->query("SELECT * FROM questions WHERE quiz_id = 1");
$questions = $stmt->fetchAll(PDO::FETCH_ASSOC);
// 显示题目
foreach ($questions as $question) {
echo "<p>{$question['question_text']}</p>";
$stmt = $db->prepare("SELECT * FROM choices WHERE question_id = ?");
$stmt->execute([$question['id']]);
$choices = $stmt->fetchAll();
foreach ($choices as $choice) {
echo "<input type='radio' name='q{$question['id']}' value='{$choice['id']}'>
{$choice['choice_text']}<br>";
}
}
随机生成选择题
动态生成选择题选项:

function generateQuestion($question, $options, $correct) {
shuffle($options);
echo "<p>$question</p>";
foreach ($options as $key => $option) {
$isCorrect = ($option == $correct) ? 'data-correct="true"' : '';
echo "<input type='radio' name='quiz' value='$key' $isCorrect> $option<br>";
}
}
generateQuestion(
"PHP 最新稳定版本是?",
["PHP 7.4", "PHP 8.0", "PHP 8.2", "PHP 8.3"],
"PHP 8.3"
);
使用会话存储结果
跨页面保持测验状态:
session_start();
if (!isset($_SESSION['score'])) {
$_SESSION['score'] = 0;
}
if ($_POST['answer'] == $correctAnswer) {
$_SESSION['score'] += 10;
}
AJAX 实时验证
无需刷新页面检查答案:
// 前端 JavaScript
$('input[type=radio]').change(function() {
$.post('check_answer.php', {
question_id: $(this).attr('name'),
answer: $(this).val()
}, function(response) {
if (response.correct) {
$(this).parent().css('background', 'lightgreen');
}
});
});
// check_answer.php
$answer = $_POST['answer'];
$correct = checkAnswerInDatabase($_POST['question_id'], $answer);
echo json_encode(['correct' => $correct]);
安全注意事项
防止表单作弊和注入:
// 验证答案是否存在
if (!array_key_exists($_POST['q1'], $possible_answers)) {
die("无效的答案选项");
}
// 数据库查询参数化
$stmt = $db->prepare("SELECT correct_answer FROM questions WHERE id = ?");
$stmt->execute([$_POST['question_id']]);
以上方法可根据实际需求组合使用,构建完整的在线选择题系统。复杂实现可能需要结合框架如Laravel或Symfony。






