I am doing a quiz in PHP code igniter. I am trying to have a function that increments the score for every correct answer. At the moment I am not passing anything to the view, and I have this in the controller:
if ($res == true)
{
$scoreIncrement = 1;
$scoreResult = $this->Starmodel->increment($scoreIncrement);
var_dump($scoreResult);
If the quess is right, I am passing value 1 to the function increment, and I am dumping the results to see what I get. Here is my function in the model:
var $score; //variable to hold the total score.
function increment($increment){
$this->score = $this->score + $increment;
return $this->score;
}
When every I run the application I always get 1 from the var_dump. Is the variable var $score; persistent in the model? Also I am clicking next, which means I am loading the function to display a new message maybe this is resetting the results. How can I have a variable in the model that will hold the current score? Thanks
use session.
You don't seem to be aware of the fact that you invoke a new PHP process with each answer.
PHP start over and over again with each post from a form or request via a href..
Your internal data is re-initialized with each request, hence the result.
Look up session to achieve persistence between requests.
You could use SESSIONS, or COOKIES to be able to have what is called as "data persistence"
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"];
?>
you can also put the current score in a hidden form field
// in your view form
echo form_hidden('currentscore',$this->score);
then pick up the value after form submit
// pass to your method to increase the score
$currentscore = $this->input->post( 'currentscore') ;
$score = $currentscore + 1 ;
opinion: using $this-> is really powerful but it can get unwieldy. if you need to pass a value to a method in a model, consider just doing it explicitly.
function incrementScore($increment,$score){
$scoretotal = $increment + $score;
return $scoretotal;
}