I am trying two simple buttons which will alter a cart's quantity by +1 or -1 depending on which button is clicked.
I set these up using 2 forms with a hidden value using post.
I then used an "if" and "ifelse" statement to determine which one (if any) was clicked.
I have compared to a very similar script doing something very similar (which works) and I can't see what I have done wrong.
The buttons
<?php
echo ' <form action="' .$_SERVER['PHP_SELF']. '" method="post">
<input type="hidden" name="bn" value="1" />';
echo '<input type="hidden" name="pr" value="' .$key. '" />';
echo '<button style="min-width:25px;height:25px;background-color:white;"><b>+</b></button>
</form>';
echo ' <form action="' .$_SERVER['PHP_SELF']. '" method="post">
<input type="hidden" name="bn" value="2" />';
echo '<input type="hidden" name="pr" value="' .$key. '" />';
echo '<button style="min-width:25px;height:25px;background-color:red;"><b>-</b></button>';
echo '</form>';
?>
And the script for dealing with the POST data;
<?php
if($_POST["bn"]=="1")
{
$_SESSION["cart"][$_POST["pr"]]["quantity"] += 1;
}
elseif($_POST["bn"]=="2") {
if($_SESSION["cart"][$_POST["pr"]]["quantity"] == 1) {
unset($_SESSION["cart"][$_POST["pr"]]);
}else{
$_SESSION["cart"][$_POST["pr"]]["quantity"] -= 1;
}
}
?>
Now the script works fine in the way that it will reload the page and will amend the quantity as per the button I clicked. Using both the normal output and print_r() I can see the session array HAS updated. However, if I now click another button on the page (the same one or different) the script will apply the update back to the original array data and not the one it should have just updated. I.e. if I sit there clicking +1 all day I will still only ever end up with 2 (the original one plus button the added one)
Please can someone help me find where I'm going wrong? Many Thanks!