想自建一套線上測驗平台?本文將帶你從零開始,結合 jQuery 前端互動、PHP 後端邏輯與 MySQL 資料儲存,完整實作一套支援動態載入題目、自動評分、即時回饋結果的線上測驗系統。閱讀前建議具備 HTML、jQuery、PHP 與 MySQL 基礎概念。
CREATE TABLE IF NOT EXISTS `quiz` ( `id` int(11) NOT NULL AUTO_INCREMENT, `question` varchar(100) NOT NULL COMMENT '題目內容', `answer` varchar(500) NOT NULL COMMENT '選項,以 ### 分隔', `correct` tinyint(2) NOT NULL COMMENT '正確選項索引(1-based)', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
範例資料:answer 欄位儲存「選項1###選項2###選項3###選項4」,correct 儲存正確選項的序號(1~4)。
<?php
include_once("connect.php"); // 資料庫連線
// 1. 查詢所有題目(不含正確答案)
$sql = "SELECT id, question, answer FROM quiz ORDER BY id ASC";
$query = mysqli_query($conn, $sql); // 建議改用 mysqli/PDO
$arr = [];
while ($row = mysqli_fetch_assoc($query)) {
$answers = explode('###', $row['answer']);
$arr[] = [
'question' => $row['id'] . '、' . $row['question'],
'answers' => $answers
];
}
$json = json_encode($arr, JSON_UNESCAPED_UNICODE);
?>
前端以 jQuery 插件 jquizzy 渲染:
$(function(){
$('#quiz-container').jquizzy({
questions: <?php echo $json; ?>,
sendResultsURL: 'data.php' // 交卷時送往評分端點
});
});
<?php
include_once("connect.php");
header('Content-Type: application/json; charset=utf-8');
$data = $_REQUEST['an'] ?? ''; // 格式: "1|3|2|4|"
$answers = explode('|', $data);
$ansCount = count($answers) - 1; // 末尾有空字串
// 取得正確答案序列
$sql = "SELECT correct FROM quiz ORDER BY id ASC";
$query = mysqli_query($conn, $sql);
$res = [];
$correctCount = 0;
$i = 0;
while ($row = mysqli_fetch_assoc($query)) {
$userAns = (int)($answers[$i] ?? 0);
$isCorrect = ($userAns === (int)$row['correct']);
$res[] = $isCorrect ? 1 : 0;
if ($isCorrect) $correctCount++;
$i++;
}
$score = $ansCount > 0 ? round(($correctCount / $ansCount) * 100) : 0;
echo json_encode(['res' => $res, 'score' => $score], JSON_UNESCAPED_UNICODE);
使用者點擊「完成」後,將答案組成 1|2|4|1|3| 字串,透過 $.getJSON 送至 data.php,收到回傳 {"res":[1,0,1,1,0],"score":60} 後,動態產生結果 HTML:
$.getJSON(config.sendResultsURL, {an: myanswers}, function(json){
if (!json) return alert('通訊失敗!');
let html = '<h2 class="qTitle">' + judgeSkills(json.score) + '<br/> 您的分數: ' + json.score + '</h2>';
json.res.forEach((v, i) => {
html += '<div class="result-row">'
+ (v === 1 ? '<div class="correct">#' : '<div class="wrong">#')
+ (i+1) + '<span></span></div></div>';
});
$('.result-keeper').html(html).show(500);
});
mysql_* 函式,實務請改用 mysqli 或 PDO 並採用預處理語句。ORDER BY RAND() 或 PHP shuffle($arr)。完成部署後,即可擁有一套輕量級、可擴充的線上測驗系統,適合教學測驗、企業訓練考核、趣味測驗等多種場景。