2015-10-26 96 views
0

我正在PHP代碼點火器中進行測驗。我試圖讓每個正確答案的分數遞增。 目前我沒有經過什麼看法,我有這個控制器:在模型(PHP,MVC)中存儲持久值

if ($res == true) 
     { 
     $scoreIncrement = 1;  
     $scoreResult = $this->Starmodel->increment($scoreIncrement); 
     var_dump($scoreResult); 

如果quess是正確的,我傳遞值1到功能增量,我傾倒的結果看看我得到了什麼。 這裏是我的模型功能:

var $score; //variable to hold the total score. 

function increment($increment){ 

     $this->score = $this->score + $increment; 
     return $this->score; 
} 

當我每次運行應用程序,我總是從獲得的var_dump 1。 是變量var $ score;在模型中持久? 此外,我單擊下一步,這意味着我正在加載函數來顯示一條新消息,也許這是重置結果。我如何在模型中有一個變量來保存當前分數? 謝謝

回答

1

使用會話。

您似乎沒有意識到您調用每個答案的新PHP過程。

PHP與來自形式或經由A HREF請求每個柱開始一遍一遍..

你的內部數據被重新初始化與每個請求,因此結果。

查找會話以實現請求之間的持久性。

http://php.net/manual/en/features.sessions.php

0

你可以使用會話或Cookie才能夠有所謂的「數據持久化」

http://php.net/manual/en/features.cookies.php

Setting new cookie 
============================= 
<?php 
setcookie("name","value",time()+$int); 
/*name is your cookie's name 
value is cookie's value 
$int is time of cookie expires*/ 
?> 

Getting Cookie 
============================= 
<?php 
echo $_COOKIE["your cookie name"]; 
?> 
0

你也可以把在當前比分隱形表格字段

// in your view form 
echo form_hidden('currentscore',$this->score); 

then p提交表格提交後的值

// pass to your method to increase the score 
$currentscore = $this->input->post('currentscore') ; 

$score = $currentscore + 1 ; 

意見:使用$ this->真的很強大,但它可能會變得笨拙。如果您需要將值傳遞給模型中的某個方法,請考慮明確地執行該方法。

function incrementScore($increment,$score){ 

     $scoretotal = $increment + $score; 
     return $scoretotal; 
}