Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/rest/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP MVC中执行两次rand()的变通方法_Php_Model View Controller - Fatal编程技术网

在PHP MVC中执行两次rand()的变通方法

在PHP MVC中执行两次rand()的变通方法,php,model-view-controller,Php,Model View Controller,嗯 我试图用php制作一个网站,从mysql中保存的问题库中向我的学生提问一系列随机问题(每页一个问题,10点后停止)。当访问website.com/random时,它启动随机控制器,然后连接到相应的模型,该模型查询数据库中的随机问题。数据库有以下列:id、question、choice1、achoice、bchoice、cchoice、dchoice、answer、correctcount、errocount。用户单击一个选项后,表单将提交到website.com/random/selecte

我试图用php制作一个网站,从mysql中保存的问题库中向我的学生提问一系列随机问题(每页一个问题,10点后停止)。当访问website.com/random时,它启动随机控制器,然后连接到相应的模型,该模型查询数据库中的随机问题。数据库有以下列:id、question、choice1、achoice、bchoice、cchoice、dchoice、answer、correctcount、errocount。用户单击一个选项后,表单将提交到website.com/random/selected。如果用户回答正确,则正确计数加1。否则,1被添加到不正确的计数中。这是模型。它又长又神秘,所以我只想总结一下。这在句法上很好

class Random_Model {
   private $databaseRow;

   public function __construct() {
      //connects to database
      //counts the number of rows and generate a random number between 1 and number of rows
      //queries the database for the random row into and puts it into an associative array
      //$this->databaseRow = the queried array
   }
   public function selected() {
      //calls $this->databaseRow
      //checks to see if the user answered correctly
      //if correct, add one to 'correctcount'
      //if incorrect, add one to 'incorrectcount'
      //header back to website.com/random where the user will answer another question
   }
   public function returnvariable() {
      return $this->databaseRow
}

问题出在这里。假设第一个随机问题的正确答案是c。另外,第二个随机问题的答案是c。如果用户单击c获得第一个答案,则第二个随机问题的正确计数将增加1。基本上,$databaseRow会在调用selected()方法后更改为下一个随机问题。因此,当它检查用户的答案是否正确时,它会检查第一个随机问题的答案和第二个随机问题的答案。有什么补救办法吗

在不过度更改模型的情况下,最简单的解决方案是将请求的id传递给模型的构造函数。如果传递了此值,则检索请求的值,否则执行随机选择逻辑

class Random_Model
{
    public function __construct($id = null)
    {
        if (null !== $id) {
            // retrieve the specified row
        } else {
            // retrieve random row
        }
    }
}

假设您在提交至网站.com/random/selected时,将具有原始问题ID和答案。因此,您应该能够正确更新

... <input type="checkbox" name="answer" value="1"/> <input type="hidden" name="questionID" value="10"/> ...
谢谢这是有道理的。
public function selected() {
  // retrieve the original question
  $oQuestion = $this->getQuestionById($_POST['questionID']);
  if ($oQuestion['answer'] == $_POST['answer']) {
    $this->addOneToCorrect($oQuestion);
  } else {
    $this->addOneToIncorrect($oQuestion);
  }
  // do the rest of your code
}