Question

Basically this is just a guessing game so that I can learn the ins and outs of cake. I'm trying to keep track of the users number of guesses on every page reload (using a variable name $user_loop). When I try to increment it, it stays static or only increments by one and stops. I've placed the increment snippet in my view also to only receive the same results. Any help would be great.

<?php

class GuessController extends AppController {

public $uses = array(); 

function beforeFilter() {

    if (!$this->Session->check('Random.Num')) {
        $this->Session->write('Random.Num', rand(1, 9));
    }
}

function create() {

    if ($this->request->is('post', 'put')) {

        $rn = $this->Session->read('Random.Num');
        $user_guess = $this->request->data['Guess']['guess'];
        $this->set('user_guess', $user_guess);

        $user_loop++      // <- Also getting undefined variable here 
        echo $user_loop; //for testing

        if ($rn == $user_guess) {   
            echo 'Cashe Cleared';
            $this->Session->delete('Random');
        }
    }
  }

}

?>
Was it helpful?

Solution

Try this :

<?php
class GuessController extends AppController {
    public $uses = array(); 

    function beforeFilter() {
        if (!$this->Session->check('Random.Num')) {
            $this->Session->write('Random.Num', rand(1, 9));
        }

        if(!$this->Session->check('user_loop')) {
            $this->Session->write('user_loop',0);
        }
    }

    function create() {
        if ($this->request->is('post', 'put')) {

            $rn = $this->Session->read('Random.Num');
            $user_guess = $this->request->data['Guess']['guess'];
            $this->set('user_guess', $user_guess);

            $user_loop = $this->Session->read('user_loop')+1;
            echo $user_loop; //for testing
            $this->Session->write('user_loop',$user_loop);

            if ($rn == $user_guess) {   
                echo 'Cash Cleared';
                $this->Session->delete('Random');
            }
        }
  }
}
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top