btrif
btrif

Reputation: 317

Php Previous Next Buttons

I'm trying to make a script which increase and decrease a variable. Afterwards this will be send to a mysql query. My problem is that the following code even if it works it has a problem. When I push the arrow (button) to increase the value it is ok, arrives to the value 4 let's say. Now I want to decrease and the problem is that it starts again with value 0, therefore it will display -1, and not from the value 4 where it remained. This is because I set in session. $_SESSION['addnum'] = $_SESSION['subnum'] ;

I tried numerous things and could not get a correct one even if I'm sure it has a quick fix. The code is as follows ( it must work even without uploading button images)

<?php
   session_start();
   // Page was not reloaded via a button press
   if (!isset($_POST['sub'])) {
       $_SESSION['subnum'] = 0; // Reset counter
   }
   
   if (!isset($_POST['add'])) {
       $_SESSION['addnum'] = $_SESSION['subnum'] ; 
   }      
?>

<form method='post'>

<input type="image" name='sub' src="includes/arrow-left.png" alt="Submit" value='-' width="32" height="32">
<input type="image" name='add' src="includes/arrow-right.png" alt="Submit" value='+' width="32" height="32">

<?php 
$var = $_SESSION['subnum']-- ;  
$var = $_SESSION['addnum']++ ; ?> 
</form>

<h3><em>Substract & Add number :  </em></h3>
<?php
echo "var = ", $var ;
?>

Thanks in advance

Upvotes: 1

Views: 79

Answers (2)

apokryfos
apokryfos

Reputation: 40653

You have 2 variables here. One which is changed when you add, and one which is changed when you subtract. And at the same time the one you change when you subtract is reset each time you load the page. The addition is really working by coincidence.

Why not simplify?

<?php
   session_start();
   // Page was not reloaded via a button press
   if (!isset($_POST['sub']) && !isset($_POST["add"])) {
       $_SESSION['num'] = 0; // Single variable to do both
   }
?>

<form method='post'>

<input type="image" name='sub' src="includes/arrow-left.png" alt="Submit" value='-' width="32">
<input type="image" name='add' src="includes/arrow-right.png" alt="Submit" value='+' width="32">

<?php 
if (isset($_POST["add"])) {   
    $_SESSION["num"] ++;
} else if (isset($_POST["sub"])) {  
    $_SESSION['num']-- ;  
}
$var = $_SESSION['num']; ?> 
</form>

<h3><em>Substract & Add number :  </em></h3>
<?php
echo "var = ", $var ;
?>

Edit: I'm assuming the image inputs somehow trigger a submit

Upvotes: 1

user2417483
user2417483

Reputation:

You are not handling the form submission.

<?php
   session_start();
   // Page was not reloaded via a button press
   if (!isset($_POST['sub'])) {
       $_SESSION['subnum'] = 0; // Reset counter
   } else {
      $_SESSION['subnum']--;
   }

   if (!isset($_POST['add'])) {
       $_SESSION['addnum'] = $_SESSION['subnum'] ; 
   } else {
      $_SESSION['addnum']++;
   }     
?>

Upvotes: 1

Related Questions