skip to Main Content

When I click on my button it removes 1 from $decr but if I click again it does not remove anything:

        <?php

function myFunction() {
    global $decr;
    $decr--;
}

if (isset($_GET['name']) && $_GET['name'] === 'true') {
    $decr--;
    $_GET['name'] = 'false';
}

?>

<a href='test.php?name=true' class="button-56"><?php echo $decr; ?></a>

I made a button I made my php function to decrement 1 but when I click a second time it does not remove anything.

2

Answers


  1. PHP itself doesn’t persist data between requests. global works only for one response, then variable recreated again on next request with initial value. All you need is use some storage (cookie, session, database, etc.)

    Login or Signup to reply.
  2. As everyone mentioned in their comments, the web pages doesn’t persist data between requests by default. To persist data, we use techniques like session, cookie, databases etc… to store data.

    We can also use hidden fields in the form to pass data to the server. The below code demonstrates it.

    <?php
    // test.php
    
    // at first check for a POST request
    if ($_POST) {
        $decr = $_POST['decr'];// read the current value from POST data
        $decr--; // decrement it
    } else {
        $decr = 10; // if not a post request, initialize $decr with 10.
    }
    ?>
    <form action="test.php" method="post">
        <!-- input the $decr value in a hidden field -->
        <input type="hidden" name="decr" value="<?php echo $decr;?>">
        <input type="button" value="<?php echo $decr;?>" onclick="submit()">
    </form>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search