phphtmlcounterincrement

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

  • There is no error in your code. Its working at my end. You need to check two points:

    1. PHP code should be above on HTML, HTML code will come after PHP code. So that $counter variable will be initialized.

    2. 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.