2016-01-22 40 views
0

好执行两次,解决方法兰特()在PHP MVC

我试图与PHP的网站来询问一系列问题随机量(每页一个问题,10后停止)从我的学生问题银行保存在MySQL中。当访问website.com/random时,它会启动随机控制器,然后连接到相应的模型,查询数据库中的随机问题。该数据库有列:id,问题,choice1,achoice,bchoice,cchoice,dchoice,答案,correctcount,wrongcount。用户点击选项后,表单将提交至website.com/random/selected。如果用户正确回答,则将1添加到正确的计数。 elseif,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。基本上,在调用selected()方法后,$ databaseRow更改为下一个随机问题。因此,当它检查用户是否正确回答时,它将检查第一个随机问题的答案以回答第二个随机问题。有没有补救措施呢?

回答

0

最简单的解决方案就是将请求的id传递给模型的构造函数。如果通过这个值,检索请求的,否则执行你的随机选择逻辑。

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

谢谢。这说得通。 – fitzpatrick221

0

假设您在提交到website.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 
}