Click counter button [PHP]
I tried to create a variable to keep the number of buttons pressed. Unfortunately I am getting this error:
Undefined variable: counter
This is my code:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$counter = isset($_POST['counter']) ? $_POST['counter'] : 0;
if(isset($_POST["button"])){
$counter++;
echo $counter;
}
}
And this is the 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>
Does anyone know what I am doing wrong?
source to share
There is no error in the code. It works at my end. You need to check two points:
-
PHP code must be above HTML, HTML code will appear after PHP code. So the variable
$counter
will be initialized. -
PHP and HTML code must be on the same page.
As the OP edited the question: So, the line $counter = isset($_POST['counter']) ? $_POST['counter'] : 0;
shouldn't be in an if-block. Of course, ** Make this line the first line of your PHP file. Then only the variable will be available for the entire page $counter
.
source to share
Alternatively, if you want to keep 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 Undefined index error
, because you are echoing
$counter
in your form, but you haven't initialized it yet. It will only exist on the first submission of the form, not on the first normal page load.
source to share
you are trying to use an undefined variable
<input type = "hidden" name = "counter" value = "<?php print $counter; ?>"; />
................................................................^
this var does not exist as the error says. guess you have a wrong setup in your code.
like php, not on the same side or above the html
source to share