我试图用Codeigner2.4做一个简单的测试,但在检查答案时遇到了一些问题。我的结构如下:控制器:猜测模型:人员视图:guessview,结果
在我的people类中,我有一个从数据库中获取所有问题并随机获取一个问题的方法。我在检查答案是否正确时遇到了问题。它总是返回错误的
function getQuestions()
{
if(!isset($questions))
{
$this->db->select("id, name, choice1, choice2, correctAnswer");
$this->db->from('questions');
$query = $this->db->get();
foreach ($query->result() as $row) {
$questions[] = $row;
}
}
return $questions;
}
function getRandomQuestion()
{
$max = count($this->getQuestions());
$randpos = rand(0, $max-1);
$question = $this->getQuestions()[$randpos];
return $question;
}
在我的控制器中:
function guess()
{
$answer = $this->input->get('answers',false);
//$questionId = $this->input->get('id',false);
//this will generate random questions.
$newQuestion = $this->people->getRandomQuestion();
$this->load->view('guessview',$newQuestion);
//this is always false
if($answer == $newQuestion->correctAnswer)
{
//do something
}
}
在我看来,我只有一个表格,每次只显示一个问题。
//更新使用您提供的功能时,我的控制器和视图中出现了一些错误。我试着在我的控制器中抓住一个问题
$question = $this->people->getRandomQuestion();
//这给了我未定义的索引correctAnswer,但它应该没有,因为数据库表具有以下结构:id,name,choice1,choice2,correctAnwer?
if($question['correctAnswer'] == $answer)
{
}
此外,当我想将数据传递到视图时,即
$question = $this->people->getRandomQuestion();
$data['question'] = $question;
$this->load->view('guessview',$data);
在我看来,对于表单值,我试着这样做:$question['name'],$question['id'],我得到了未定义的索引名称,id等。
我的表格来自guessview.php
<form id= "form1" class="form" action="<?php echo base_url();?>guess/people" method='POST'>
<input type=hidden name=id value="<?php echo $question['id'] ?>">
<label><?php echo $question['name'] ?>
<div class="radio">
<label>
<input type="radio" id='rad1' name="answerswers" value="<?php echo $question['choice1'] ?>">
<?php echo $question['choice1'] ?>
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="answerswers" value="<?php echo $question['choice2'] ?>">
<?php echo $question['choice2'] ?>
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="answerswers" value="<?php echo $question['correctAnswer'] ?>">
<?php echo $question['correctAnswer'] ?>
</label>
<div>
<input type=submit name="sub" value="Answer">
</div>
</form>
我发帖的原因被认为是控制器功能的问题。当我试图检查用户回答是否正确时,似乎总是错误的。就像用户回答上一个问题的内容与当前问题的正确答案进行比较。
我试着输入单选按钮和id(放在一个隐藏字段中)如果这些返回false,则意味着不显示任何问题并显示第一个问题。否则,如果有输入,则根据id获取问题,并将问题的correctAnswer与用户选择的内容进行比较。(但正如我上面所说,这永远是错误的)。我回家后会公布这个方法。
您可以在单个模型函数中完成
function getRandomQuestion()
{
$sql = "SELECT * FROM questions ORDER BY RAND() LIMIT 1 )";
$query = $this->db->query($sql);
$result = $query->result_array();
$count = count($result);
if (empty($count) ||$count > 1) {
echo "Inavliad Question";
}
else{
return $result;
}
}