开发者

keep adding value in php

开发者 https://www.devze.com 2023-04-12 03:05 出处:网络
Initially,the $number = 0. After 1st time clicking Add button, the value becomes 10. When 2nd time clicking, the value is changed to 20. then 3rd time is 30, 4th time 40.

Initially,the $number = 0. After 1st time clicking Add button, the value becomes 10. When 2nd time clicking, the value is changed to 20. then 3rd time is 30, 4th time 40.

Below is my code, is there anyone know how to fix it? Thanks!

<?php
      $number = 0;
      if(isset($_POST['add'])){

          $number = $number +10;
       }
?>
<html>
    <head>

    </head>
    <body>
        <form method="post" action="<?php echo $_SERVER['SCRIPT开发者_开发技巧_NAME']; ?>">
            <?php echo $number; ?>
            <input type="submit" name="add" value="Add" />
        </form>
    </body>
</html>


  <input type="hidden" value="<?php echo $number ?>" name="number" />

Now change the $_POST['add'] to $_POST['number'] And $number = $_POST['number'] + 10;


This is fundamental to how PHP works.

There is no 'state' in between requests. This means that everything will be forgotten for every request. So if you want to retain data, you have to store it somewhere.

A couple of options:

  • A database such as MySQL
  • A session
  • A cookie
  • A caching system such as APC


First of all, your PHP needs a little adjusting:

<?php
    $number = ($_POST['add'] != '') ? 0 : $_POST['add'];
    $number += 10;
?>
<html>

Then add a hidden input above the <input type="submit">, like so:

<input type="hidden" name="add" value="<?php echo $number; ?>">


Use the session variable to retain the value per page request. Simple variable values is destroyed once script finish execution. Session variable will keep the value.

Read more about session

or use the database.


You need to save the value somehow. Either you use a database, like MySql, or you could save the value in a session variable.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号