[Solved] Button click counter [PHP]
I tried to create a variable to store a count of button clicked. Unfortunetlly i get this error:
Undefined variable: counter
It’s my code:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$counter = isset($_POST['counter']) ? $_POST['counter'] : 0;
if(isset($_POST["button"])){
$counter++;
echo $counter;
}
}
And it’s a form:
<form action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method = post>
<input type = "submit" name = "button" value = "Submit" >
<input type = "hidden" name = "counter" value = "<?php print $counter; ?>"; />
</form>
Anybody know what i’m doing wrong?
Solution #1:
There is no error in your code. Its working at my end. You need to check two points:
-
PHP code should be above on HTML, HTML code will come after PHP code. So that
$counter
variable will be initialized. -
PHP and HTML code should be on same page.
As OP edited the question: So, the line $counter = isset($_POST['counter']) ? $_POST['counter'] : 0;
should not be in if-block. To be sure, ** Make this line as a first line of PHP file. Then only $counter
variable will be available for whole page.
Solution #2:
Alternatively, if you want to save the counter, you can use sessions. Like this:
session_start();
// if counter is not set, set to zero
if(!isset($_SESSION['counter'])) {
$_SESSION['counter'] = 0;
}
// if button is pressed, increment counter
if(isset($_POST['button'])) {
++$_SESSION['counter'];
}
// reset counter
if(isset($_POST['reset'])) {
$_SESSION['counter'] = 0;
}
?>
<form method="POST">
<input type="hidden" name="counter" value="<?php echo $_SESSION['counter']; ?>" />
<input type="submit" name="button" value="Counter" />
<input type="submit" name="reset" value="Reset" />
<br/><?php echo $_SESSION['counter']; ?>
</form>
By the way, your current code will show an Undefined index error
because you are echoing
$counter
on your form but you haven’t initialized it yet. It will only exist, upon first form submission, not upon first normal load of the page.
Solution #3:
Variable is not defined because of this u get this error.
To hide this error write this in top of page error_reporting(0)
.
Solution #4:
you try to use a undelaired variable
<input type = "hidden" name = "counter" value = "<?php print $counter; ?>"; />
................................................................^
this var doesn’t exists as the error says. guess you have a wrong setup of your code.
like the php is not on the same side or not above the html