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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With