I am a beginner at coding and I am printing a number (36 here) and I have 4 buttons. Pressing each button should subtract from the amount remaining. So when I press the '3' button, the amount remaining is 33 but after this when I press the button '4', the value displayed should be 29, but what I get is 32 instead.
How do I make it so the value of variable mleft is not reset to 36 each time I press a button?
<div >
<form method="post">
<button value=1 name="pressed">1</button>
<button value=2 name="pressed">2</button>
<button value=3 name="pressed">3</button>
<button value=4 name="pressed">4</button>
</form>
</div>
<?php
$mleft = 36;
if (isset($_POST['pressed'])) {
echo $_POST['pressed'];
$mleft = $mleft -= $_POST['pressed'] ;
}
?>
<div >
<div id="matchn">
<h3>Matchsticks left</h3>
<h1><?=$mleft?></h1>
</div>
</div>
CodePudding user response:
Each time you post the form, you set $mleft to 36 before you subtract from it.
If you want the value to persist between calls, use a session variable and subtract from that.
<?php
session_start();
?>
<div >
<form method="post">
<button value=1 name="pressed">1</button>
<button value=2 name="pressed">2</button>
<button value=3 name="pressed">3</button>
<button value=4 name="pressed">4</button>
</form>
</div>
<?php
$mleft = $_SESSION['mleft'] ?? 36;
if (isset($_POST['pressed'])) {
echo $_POST['pressed'];
$mleft -= $_POST['pressed'] ;
}
$_SESSION['mleft'] = $mleft;
?>
<div >
<div id="matchn">
<h3>Matchsticks left</h3>
<h1><?=$mleft?></h1>
</div>
</div>
CodePudding user response:
Now on every page refresh you declare $mleft = 36; and after second button press this variable is not e.g. 29, but 33. To fix it you can set $_SESSION variable, for example:
session_start(); // To set session variables tou must start it
if (!isset($_SESSION['mleft'])) { // Check if mleft exists, because setting up every
$_SESSION['mleft'] = 36; // every page refresh will not
} // substract from variable
if (isset($_POST['pressed'])) {
echo $_POST['pressed'];
$_SESSION['mleft'] = $_SESSION['mleft'] -= $_POST['pressed'] ; // Substract
}
CodePudding user response:
Just a friendly suggestion, you're probably a lot better off doing this in javascript like so...
let counterContainer = document.querySelector('h1');
let matchSticksLeft = parseInt(counterContainer.innerText);
function subtract(amount){
counterContainer.innerText = matchSticksLeft -= amount;
}
<div >
<button value=1 name="pressed" onclick="subtract(1)">1</button>
<button value=2 name="pressed" onclick="subtract(2)">2</button>
<button value=3 name="pressed" onclick="subtract(3)">3</button>
<button value=4 name="pressed" onclick="subtract(4)">4</button>
</div>
<div >
<div id="matchn">
<h3>Matchsticks left</h3>
<h1>36</h1>
</div>
</div>
