'Increase value by 1 on button click
I am trying to make this code increase the value of $clicks by 1 every time I click the button, but I cannot seem to get it working. Any inputs?
<form action="" method="post">
<input type="submit" name="click_button" value="Click..">
</form>
<?php
$clicks = 0;
echo $clicks;
if (isset($_POST['click_button'])) {
$clicks = $clicks + (1);
}
Solution 1:[1]
It's because as soon as the page get's reloaded, $clicks goes away. You need to store $clicks in the $_SESSION superglobal. Then, the value of $clicks won't go away every time the page is reloaded.
<form action="" method="post">
<input type="submit" name="click_button" value="Click..">
</form>
<?php
session_start();
if (isset($_POST['click_button'])) {
$_SESSION['clicks'] += 1 ;
} else {
$_SESSION['clicks'] = 0;
}
echo($_SESSION['clicks']);
NOTE: don't forget to include session_start();
at the very beginning of the script. Otherwise, the script won't have access to $_SESSION
Solution 2:[2]
Actually, PHP isn’t exactly working like JavaScript. After you press a button, the value is posted to the PHP Web Server, which increments the value. BUT then, after that, the $_POST[];
value remains the same, even after you let go of the button. So, if you clicked it once, even if you clicked it again, the $_POST[];
value just remains the same, therefore not making any change to the clicks;
variable after incrementing it once. The only way is to use JavaScript and find a way to connect it to your code.
P.S. There is nothing wrong with that form action=“”
part of your code. Everything is right with your HTML. You just need to convert the PHP code to JavaScript.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Native Coder |
Solution 2 | Jasper Ko |