即使值相同,数据比较也会失败

时间:2011-08-10 11:48:21

标签: cakephp

我正在研究测验测试的代码,这里

            function run($id){
            //Is this the first question ?
            if($this->data){
                $question_no = $this->Session->read('Test.qno'); //0
                $last_answer = $this->Session->read('Test.last_answer');
                $question_no = $question_no + 1;                 //1
                $this->Session->write('Test.qno',$question_no);  //Test.qno = 1
                $this->Session->setFlash('last_answer'.$this->data['Test']['answer']);
                $this->redirect($this->referer());

                if($this->data['Test']['answer']==$last_answer){
                    $score = $this->Session->read('Test.score');
                    $score = $score + 1 ;
                    $this->Session->write('Test.score',$score);
                    $this->Session->setFlash('Correct answer');
                }
            }

            $question_no = $this->Session->read('Test.qno');    //question_no =
            if(!$question_no){
                $question_no = 0;
                $this->Session->write('Test.qno',$question_no);
                $this->Session->write('Test.score',0);
            }
            $question = $this->Test->Question->find('first',array('conditions'=>array('Question.test_id ='=>$id),'offset'=>$question_no));
            $answer = $question['Question']['answer'];
            $this->Session->write('Test.last_answer',$answer);
            if(empty($question)){
                $score = $this->Session->read('Test.score');
                $this->Session->setFlash('Your Score is '.$score);
                $this->Session->write('Test.qno',0);
                $this->redirect(array('controller'=>'States','action'=>'index'));
                }
            else{
                $this->set(compact('question'));
                }
        }

这里数据比较失败,即使它们都保持相同的值也可以告诉我为什么,这里$ last_answer从会话中检索并保存一个数字。

$ this-> data ['Test'] ['answer']取自带有单选按钮的表单

1 个答案:

答案 0 :(得分:0)

添加

debug( '"'.$this->data['Test']['answer'].'"' );
debug( '"'.$last_answer.'"' );

确认它们真的是一样的。

同时确保会话没有问题(即条件为真,但内部代码不执行任何操作):在if块中添加debug( "true" );并确认您看到了消息。

看到整个代码后,

更新

if块前面有$this->redirect()!当然,您最初发布的代码没有做任何事情,因为您在执行之前将用户重定向到另一个页面