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?

+3


source to share


4 answers


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

.

+1


source


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.

+3


source


The variable is undefined because of this u gets this error.

To hide this error, write this at the top of the page error_reporting(0)

.

Check this .. as for a specific variable?

0


source


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

0


source







All Articles