Page 1 of 1

Session variables keep resetting

Posted: Thu Apr 02, 2009 1:39 pm
by phpnitemare
Hi,


I have a problem with variables getting reset each time the main index.php is loaded should a user wish to go back to view items after adding one to the basket. I therefore added an initial check to set the default values once based on sessioncode being equal to 0, after which the variable is assigned sessionid().

Therefore now I am unable to reset the values, i have seen a function session_destroy/unset. Would this help in this situation, if I was to add a button, 'clear basket' which ran a function similar would this clear the session or at least reset the core values?


Code: Select all

$_SESSION["sessioncode"] = 0;
$sessioncode = $_SESSION["sessioncode"];
if($_SESSION["sessioncode"]=0){
$pointer = 0;
$_SESSION["pointer"] = $pointer;
}
$sessioncode = session_id();

Re: Session variables keep resetting

Posted: Thu Apr 02, 2009 1:54 pm
by greyhoundcode
In short, replace = with == when making a comparison.

In your code you are evaluating an assignment - you are assigning zero to $_SESSION['sessioncode'], and the outcome is true:

Code: Select all

if ($_SESSION["sessioncode"] = 0)
{
    $pointer = 0;
    $_SESSION["pointer"] = $pointer;
}
What you should do instead is compare zero against $_SESSION['sessioncode']:

Code: Select all

if ($_SESSION['sessioncode'] == 0)
{
    $pointer = 0;
    $_SESSION["pointer"] = $pointer;
}

Re: Session variables keep resetting

Posted: Thu Apr 02, 2009 2:49 pm
by Apollo
phpnitemare wrote:if($_SESSION["sessioncode"]=0)
you probably meant == right? ;)

(edit) oh, too late I guess, didn't see the above reply before.

By the way, coding tip of the day - the above issue is a typical reason why

Code: Select all

if (0==$x)
is better than

Code: Select all

if ($x==0)
because they do exactly the same, except the first won't allow you to make that single = mistake.