我正在使用 PHP 和 MYSQL 构建一个简单的测验程序。
测验旨在一次显示一个问题;问题为多项选择题(每个问题有 4 个可能的答案)
如果玩家选择正确,他将进入下一个问题;
如果他选错了,测验就会结束。
首先,我设计的测验如下:
(1)创建一个数据库表,其中包含1500个问题。该表包含以下列:
ID (primary key)
QUESTION (the question itself)
A1 (first answer)
A2 (second answer)
A3 (third answer)
A4 (fourth answer)
CORRECT (the correct answer --- which is one of the above A1 to A4)
(2) 然后,我的 PHP 代码被设计为按顺序(使用 ID 作为参考)一一挑选问题。
因此,当用户开始玩时,他从问题 1 开始,然后是问题 2,依此类推。
(3) 为了使它更有趣,当用户在我的测验网站上注册为玩家时,我在数据库中添加了一个额外的列 (begin_id),其默认值为“1”。每次用户回答问题时,此列都会更新为该问题的“ID”。意思是,它记录了用户回答的最后一个问题(无论是错误还是正确)。这样:下次用户登录并进行测验时,他不会从问题 1 开始。相反,他从列表中的下一个问题开始。 (这意味着,用户永远不会两次看到相同的问题!)
这是代码:
// Query database
$get_question = "SELECT * from questions_table where id = $begin_id";
$result_get_question = mysqli_query($conn, $get_question);
$row_get_question = mysqli_fetch_array($result_get_question);
// Assign database response to variables
$question = $row_get_question['question'];
$a1 = $row_get_question['a1'];
$a2 = $row_get_question['a2'];
$a3 = $row_get_question['a3'];
$a4 = $row_get_question['a4'];
$correct = $row_get_question['correct'];
// Check user answer
if (isset($_POST['submit'])) {
$selected_radio = $_POST['response'];
if ($selected_radio == $correct)
echo "THAT ANSWER IS CORRECT";
else
echo "THAT ANSWER IS WRONG!";
}
而且,一切都很顺利!
现在,我决定让它变得更加“高效”;我决定简单地修改我的 PHP-SELECT 语句,以随机选择问题,而不是按顺序选择问题。
这很容易,特别是因为有很多关于如何完成此操作的在线教程。
这是我使用的代码(最简单的代码):
SELECT * from questions_table order by rand() limit 1;
就选择随机问题而言,这是有效的。然而,有问题的是:无论用户选择什么答案,它总是错误的答案!!
由于某种原因,从数据库中选择随机问题弄乱了“正确答案/错误答案“我的 PHP 代码中的逻辑。
不知道会出什么问题。
UPDATE
$get_question = "SELECT * from questions_table where id = $begin_id";
$result_get_question = mysqli_query($conn,$get_question);
$row_get_question = mysqli_fetch_array($result_get_question);
$question_id = $row_get_question['question_id'];
$question = $row_get_question['question'];
$a1 = $row_get_question['a1'];
$a2 = $row_get_question['a2'];
$a3 = $row_get_question['a3'];
$a4 = $row_get_question['a4'];
$correct = $row_get_question['correct'];
<br>
<form method ="post" action ="">
<input type="radio" name="response" value="<?=$a1?>"><?=$a1?><br>
<input type="radio" name="response" value="<?=$a2?>"><?=$a2?><br>
<input type="radio" name="response" value="<?=$a3?>"><?=$a3?><br>
<input type="radio" name="response" value="<?=$a4?>"><?=$a4?><br>
<input type="hidden" name="question_id" value="<?= echo $question_id?>"
/> <br>
<Input type = "submit" Name = "submit" Value = "Answer"> </form>