使用 php 和 mysql 每个正确答案的分数

Points per right answer using php and mysql

我想弄清楚如何创建一个系统,让用户每周回答一堆问题,并在每个正确答案中得分。管理员将在下周添加正确答案,因此用户答案必须存储在数据库中。

希望帮助如何使用 php 和 mysql 来解决这个问题。谢谢!

MYSQL:

  1. 您可以使用 WEEK(created_at)=WEEK(NOW()) 来获取本周的答案。
  2. GROUP BY user_id 按用户分组。
  3. COUNT(*) 总正确答案。
  4. JOIN 到 table 有了正确的答案才能得到正确的答案。

您应该创建:

  1. questions.php 页面 HTML(用户回答 问题)
  2. MySQL 数据库(用户名,答案 1,答案 2 ...) (在数据库中插入答案)
  3. admin.php(管理员可以更正的地方 答案)

您需要几页:

1) 问题页面:

questions.php 页面中,您可以在每个问题下有一个表单,允许用户 select 复选框:

<form action="answers_submitted.php" method="POST">
What is 1 + 5 equal to?<br>
  <input type="radio" name="answer0" value="3"> 3 
  <input type="radio" name="answer0" value="6"> 6 
  <input type="radio" name="answer0" value="99"> 99 <br>
  <input type="submit" value="Send Answers">
</form>

2) 答案提交页面:

一旦用户单击 "Send Answers"answers_submitted.php 页面就必须检索这些值。检索答案后,将这些答案与正确答案进行比较以获得分数。例如,如果总共有 4 个问题:

<?php

//array containing the right answers
$array_of_answers = array(6,2,"food", 33, "books");

$score = 0;//this value will contain the score once all the code
           //has been executed.

for ($i = 0; $i<4; $i++)
{
  $string = 'answer'.$i;
  if(isset($_POST[$string]))
  {
    if ($_POST[$string] == $array_of_answers[$i])
    $score++;
  }
}

?>

然后可以将该分数保存到数据库服务器中,例如 MySQL,然后在下周显示给用户。此代码也可以在 answers_submitted.php 页上完成。这是一个如何将信息发送到数据库的简化示例,但我建议您阅读有关此事的完整教程:

$sql = "UPDATE users SET score = {$score} WHERE id = {$_SESSION['user_id']}";
$stmt = $conn->query($sql);

由于 $score 值不是用户直接输入的,并且由于 $_SESSION['user_id'] 值是在服务器上生成的,因此在这种情况下不需要准备语句和绑定参数,THOUGH 在大多数情况下,需要这些来防止 sql 注入。一些编码人员甚至在所有情况下(即使不需要)都应用这些方法只是为了养成使用它们的习惯,所以在编写自己的代码时请记住这一点!

你可以这样设计:

有3张桌子

Users (id, username, password, is_admin)
Questions (id, question, points, creation_date)
Answers (id, answer, question_id, is_correct, user_id)

三个动作

    i) add_question
   ii) answer_question
  iii) select_correct_answer

用户创建和身份验证不是这个问题所特有的,这就是我不谈论它的原因。

在上面列出的三个动作中,我将仅解释第三个,假设其他两个是不言自明的:

select_correct_answer

    ***This action would take question_id as argument***
    >> admin selects correct answer for a question (simply sets is_correct = 1)
    >> all answers for that question are extracted from the db
    >> each answer is compared with the answer supplied by admin
    >> for each question that matches, the user that answered is extracted from the db and the point for that question is added to the user's total points.

希望这对您有所帮助。