通过每次重复的表单提交增加post的值


Incrementing the value of the post by every repeated form submission

我有一个表单sender,它将值6发送到另一个表单receiver。我想要实现的是将sender的发布值存储到receiver中的变量中,然后每次sender发布时都增加变量。然后打印更新后的变量

这就是我想做的

$val= $_POST['val'];
$limit = 6 + $val;
echo $limit;

得到的结果是12。但是我想要的是

  1. 第一次发帖后结果= 12

  2. 第二次发帖后结果= 18

On and On…

NB:$_POST['val'] = 6;
session_start();
$limit = 6;
if(!isset($_SESSION['lastLimit'])) {
    $_SESSION['lastLimit'] = 0;
}     
if(!empty($_POST)) {    
    $_SESSION['lastLimit'] = $_SESSION['lastLimit'] + $limit;
    $postedValue = $_POST['val'] + $_SESSION['lastLimit'];
    echo $postedValue;
}

因为web是无状态的,即脚本不记得上次页面/表单执行时发生的任何事情,receiver脚本不记得上次运行时发生的任何事情。

但别慌,有办法的。它被称为SESSION,你可以在会话中存储数据,当这个用户下次连接到你的网站时,这些数据就可用了。在PHP中是这样使用的。会话被链接到这个特定的连接到一个特定的用户。

receiver.php

<?php
// must be run at top of script, before any output is sent to the new form
session_start();   
// did the form get posted and is the variable present
// or replace POST with GET if you are using an anchor to run the script
if ( $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['val']) {
    if ( isset($_SESSION['limit'] ){
        // increment the limit
        $_SESSION['limit'] += (int)$_POST['val'];
    } else {
        // initialize the limit
        $_SESSION['limit'] = (int)$_POST['val'];
    }
    echo 'Current value of limit is = ' $_SESSION['limit'];
} else {
    // something is not right
    // direct this user to some basic page like the homepage or a login
    header('Location: index.php');
}            

您需要一个中间层来存储该值。可用选项:

1)全局静态值

2)会议

3)文件

4)数据库

我建议使用全局值或会话,因为你想要存储的数据不是那么大,而且很容易满足需求。

我不会编写语法来将它存储在会话中,因为许多人已经提到过它。我只是想澄清问题的情况和可能的解决方案。

可以将$ limit存储为全局变量

global $val;
$val += $_POST['val'];
$limit = 6 + $val;
echo $limit;