-2

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.

Alex
  • 1
  • 3
    Does this answer your question? [Is PHP or PHP based web framework stateful or stateless?](https://stackoverflow.com/questions/6327243/is-php-or-php-based-web-framework-stateful-or-stateless) – luk2302 May 21 '23 at 19:08

3 Answers3

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>
ash.dev
  • 21
  • 3
  • the data is not kept because if I reopen on another page the data returns to 10 ? – Alex May 22 '23 at 14:59
  • @Alex You should store your data somewhere if you want to persist data between requests. For example: Session https://www.php.net/manual/en/session.examples.basic.php – ash.dev May 24 '23 at 06:13
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.)

lezhni
  • 292
  • 2
  • 12
0

Try this, it is a good start for what you are trying to do. Use sessions when you want to keep the value alive from page load to page load.

<?php
// this has to be the first thing that php sees on the page
session_start();

// make sure you create the variable the first time or you will get a php error
if (!isset($_SESSION['decr'])) { 
    $_SESSION['decr'] = '0';
}

if (isset($_GET['name']) && $_GET['name'] === 'true') {
    $_SESSION['decr']--;
    $_GET['name'] = 'false';
}
?>
<a href='test.php?name=true' class="button-56">Num: <?php echo $_SESSION['decr']; ?></a>