store a value from SESSION and use it to decrement size

crescue
crescue used Ask the Experts™
on
Hi how can I retrieve a value from SESSION.  Store that value in a variable.  Decrement by one the value of that variable and store it back into SESSION.  
What I'm trying to do is assume I have a $_SESSION["counter"] with the value of 30

I would like to store that value in a variable when the USER enters the program
   Decrement the value by 1 when a user presses a button (it calls a function)
   and continue to use the same value (decrement by 1) when the user presses the button again

I have --->  $tok = $_SESSION["counter"]
                             when the program starts
                   $_SESSION["counter"] = $tok -= 1;
                               when the user presses the button, and it calls a function (I have   $_SESSION ["counter"] = $tok -= 1;   inside the FUNCTION)

My problem is that when the user enter the php program, it retrieves a variable of 30, when he presses the button, it does store the value of 29 in $_SESSION["counter"] when the user presses the button, but if the user re-presses the button, it stores the SAME VALUE of 29

I have tried to retrieve the $_SESSION... value INSIDE the function, so I can retrieve the current value from 'counter', but it gives me an error.

Thanx for ur help          
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
hi, what about $_SESSION["counter"] -= 1;  ?
or to split your code to two rows:
$tok -= 1;
$_SESSION["counter"] = $tok;

Author

Commented:
I have tried that, but it works only the first time the USER presses the button.  If the user presses the button again, it gill get the ORIGINAL value, it doesn't load the NEW VALUE (I can't want to REFRESH or RELOAD the page for this matter)
Where and how can I store the original value and go grom there
Altin BardhiSoftware Engineer

Commented:
I have just build one example for this query.

Hope this helps a little.

Regards
<?php //click_counter.php
session_start();
$start = 30 ;

if(isset($_POST['clicked'])){
//Substract one from the value of $_SESSION["counter"] and asign it to $store
$store = $_SESSION["counter"] - 1; 
//Get the value from $store and asign it back to $_SESSION["counter"] after the substraction has taken place
$_SESSION["counter"] = $store;
 
//Print the values
echo"The button has been clicked " .  ($start - $_SESSION["counter"]) . " times. \n";
 
echo"The session counter holds the value of: " .  $_SESSION["counter"] . ".";
 
}else{
 //Set $tok default value when no click has occurred on page load
$_SESSION["counter"]=30;
}


?>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>

<body>

<form action="#" method="post">
<input type="hidden" name="clicked" />
<input type="button" name="btn" value="Test Clicked Counter" onclick="this.form.submit();" />
</form>

</body>
</html>

Open in new window

Success in ‘20 With a Profitable Pricing Strategy

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Commented:
It sounds like your session is restarting each time. This might mean that you're not using session_start() before using your $_SESSION variables or it might mean you don't have cookies enabled in your browser.

Commented:
Oh, and a shortcut for decrementing by 1 is to just $var--, or incrementing is $var++, like this:

$_SESSION["tok"]--; // Decrement by 1
Software Engineer
Commented:
Of course if you are setting sessions you are setting cookies, (If the cookies are not enabled on the client side, the  $_SESSION will not be able to set a cookie, therefore causing the script to fail.) except in different locations and of course you can use $_SESSION["counter"]--; to subs tract by one or the opposite to add by one like in the following example.
<?php //click_counter.php
session_start();
$start = 30 ;

if(isset($_POST['clicked'])){

//If entered here, substract one from the value of $_SESSION["counter"] and asign it to back $_SESSION["counter"]
$_SESSION["counter"]--;
 
//Print the values
echo"The button has been clicked " .  ($start - $_SESSION["counter"]) . " times. \n";
 
echo"The session counter holds the value of: " .  $_SESSION["counter"] . ".";
 
}else{
 //Set $tok default value when no click has occurred on page load
$_SESSION["counter"]=30;
}


?>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>

<body>

<form action="#" method="post">
<input type="hidden" name="clicked" />
<input type="button" name="btn" value="Test Clicked Counter" onclick="this.form.submit();" />
</form>

</body>
</html>

Open in new window

Most Valuable Expert 2011
Top Expert 2016

Commented:
Here is a two part answer.

First, please install and run this script - if the session cheese value goes up by one every time you click, your sessions are almost certainly working correctly.

Next I will show you how to set the value to 30 and decrement it by one each time.  You do not want to copy the value in the $_SESSION array - you want to use the value in the array in your functions and classes and mainline code.  $_SESSION is directly addressable in every variable scope and namespace, so the act of copying it only confuses your programming.
<?php // RAY_session_test.php
error_reporting(E_ALL);

// MAN PAGE HERE: http://us.php.net/manual/en/function.session-start.php

// START THE SESSION (DO THIS FIRST IN EVERY PHP SCRIPT ON EVERY PAGE)
session_start();

// SEE IF THE SUBMIT BUTTON WAS CLICKED
if (isset($_POST['fred']))
{

// SEE IF THE CHEESE VARIABLE IS SET IN THE SESSION ARRAY
    if(!isset($_SESSION['cheese']))
    {

// IF CHEESE IS NOT SET, SET IT TO ONE
        $_SESSION['cheese'] = 1;

    } else {

// IF CHEESE IS SET, ADD ONE TO IT
        $_SESSION['cheese']++;
    }
}
// END OF SCRIPT - SUPPRESS NOTICES IN THE HTML PART
error_reporting(E_ALL ^ E_NOTICE);
?>
<html><head><title>Session Test</title></head>
<body>
Currently, $_SESSION["cheese"] contains: <?php echo $_SESSION['cheese']; ?> <br/>
<form method="post">
<input type="submit" value="click" name="fred">
</form>
</body>
</html>

Open in new window

Most Valuable Expert 2011
Top Expert 2016

Commented:
If your session test worked, you can use this pattern to achieve your objective.  Whether you choose to package a one-line subtraction inside a function is up to you (I would not do that) but in any case your code will be clearer and less error-prone if you simply refer to the session variables directly.

Best regards, ~Ray
<?php // RAY_temp_crescue.php
error_reporting(E_ALL);

// SET A SESSION COUNTER TO 30 AND DECREMENT IT WHENEVER THE BUTTON IS PUSHED

// ALWAYS START THE SESSION.  SEE: http://us.php.net/manual/en/function.session-start.php
session_start();

// IF THE COUNTER IS NOT SET, SET IT
if (!isset($_SESSION["counter"])) $_SESSION["counter"] = 30;

// IF THE SUBMIT BUTTON WAS CLICKED
if (isset($_POST['fred']))
{
    // DECREMENT THE SESSION COUNTER
    $_SESSION["counter"]--;
}

// IF THE SESSION COUNTER HAS GONE TO ZERO, EXPLODE
if ($_SESSION["counter"] == 0) echo "<br/>BOOM!\n";

// END OF PHP - DROP INTO HTML
?>


<form method="post">
<input type="submit" value="COUNTER IS <?php echo $_SESSION["counter"]; ?>" name="fred">
</form>

Open in new window

Author

Commented:
THanx

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial