PHP实现题库源码
以下是一个基于PHP的简单题库系统实现方案,包含核心功能和代码示例:
数据库设计
创建MySQL数据库表结构存储题目和答案:
CREATE TABLE `questions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`question_text` text NOT NULL,
`question_type` enum('single','multiple','true_false') NOT NULL,
`difficulty` tinyint(4) DEFAULT 1,
`category_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `answers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`question_id` int(11) NOT NULL,
`answer_text` text NOT NULL,
`is_correct` tinyint(1) DEFAULT 0,
PRIMARY KEY (`id`)
);
题目添加功能
实现后台题目添加的表单处理:
// 添加题目处理
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$questionText = $_POST['question_text'];
$questionType = $_POST['question_type'];
$stmt = $pdo->prepare("INSERT INTO questions (question_text, question_type) VALUES (?, ?)");
$stmt->execute([$questionText, $questionType]);
$questionId = $pdo->lastInsertId();
// 处理答案选项
foreach ($_POST['answers'] as $answer) {
$isCorrect = isset($_POST['correct_answers'][$answer['id']]) ? 1 : 0;
$stmt = $pdo->prepare("INSERT INTO answers (question_id, answer_text, is_correct) VALUES (?, ?, ?)");
$stmt->execute([$questionId, $answer['text'], $isCorrect]);
}
}
题目展示功能
前端展示题目及选项:
// 获取题目列表
$stmt = $pdo->query("SELECT * FROM questions");
$questions = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($questions as $question) {
echo "<div class='question'>";
echo "<h3>{$question['question_text']}</h3>";
// 获取对应答案
$stmt = $pdo->prepare("SELECT * FROM answers WHERE question_id = ?");
$stmt->execute([$question['id']]);
$answers = $stmt->fetchAll();
foreach ($answers as $answer) {
echo "<label><input type='radio' name='q{$question['id']}' value='{$answer['id']}'>";
echo "{$answer['answer_text']}</label><br>";
}
echo "</div>";
}
答案验证功能
提交后验证用户答案:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$score = 0;
foreach ($_POST as $key => $userAnswer) {
if (strpos($key, 'q') === 0) {
$questionId = substr($key, 1);
// 获取正确答案
$stmt = $pdo->prepare("SELECT id FROM answers WHERE question_id = ? AND is_correct = 1");
$stmt->execute([$questionId]);
$correctAnswers = $stmt->fetchAll(PDO::FETCH_COLUMN);
if (in_array($userAnswer, $correctAnswers)) {
$score++;
}
}
}
echo "您的得分: {$score}";
}
扩展功能建议
- 添加分类管理功能
- 实现题目随机组卷
- 添加题目难度分析
- 开发用户答题历史记录
- 实现题目导入导出功能
系统可采用MVC架构组织代码,建议使用PDO进行数据库操作防止SQL注入。前端可使用Bootstrap等框架优化界面展示效果。






