如何在提交 2 个表单后将变量保留在 php 中

How to keep variables in php after 2 form submits

我的 php 代码有问题。我有 2 个 html 表单,我需要在用户提交每个表单后在输入中显示输入数据。我有一个问题,用户提交表单 1 时数据在表单中正确显示,但是当用户提交表单 2 时,表单 1 中的数据被删除,我希望两个表单都显示输入数据。下面是用于演示的简化代码。

<?php
$name1 = "";
$email1 = "";
$name2 = "";
$email2 = "";
?>

<?php
if (isset($_POST['submit1'])) {
$name1 = $_POST['name1'];
$email1 = $_POST['email1'];
}

if (isset($_POST['submit2'])) {
$name2 = $_POST['name2'];
$email2 = $_POST['email2'];
}
?>

<form action="index.php" method="post">
Name: <input type="text" name="name1" value="<?php echo $name1; ?>"><br>
E-mail: <input type="text" name="email1" value="<?php echo $email1; ?>"><br>
<input type="submit" value="send" name="submit1">
</form>
<form action="index.php" method="post">
Name: <input type="text" name="name2" value="<?php echo $name2; ?>"><br>
E-mail: <input type="text" name="email2" value="<?php echo $email2; ?>"><br>
<input type="submit" value="send" name="submit2">
</form>

您可以使用 PHP 个会话。当提交页面上的表单时,您可以将 $_POST 变量存储在 $_SESSION 中,然后仅使用 $_SESSION 变量来填写表单。请参阅下面的代码:

<?php
    session_start(); //start the session
    if(isset($_POST)){ //check to see if a form has been submitted
        // merge the $_SESSION & $_POST arrays, 
        // this will overwrite session variables with new post variables but keep old post variables that haven't been submitted
        $_SESSION = array_merge($_SESSION,$_POST); 
    }
 

    $name1 = "";
    $email1 = "";
    $name2 = "";
    $email2 = "";
?>

<?php
if (isset($_SESSION['submit1'])) { //uses $_SESSION instead of $_POST
    $name1 = $_SESSION['name1'];
    $email1 = $_SESSION['email1'];
}

if (isset($_SESSION['submit2'])) { //uses $_SESSION instead of $_POST
    $name2 = $_SESSION['name2'];
    $email2 = $_SESSION['email2'];
}
?>

<form action="index.php" method="post">
    Name: <input type="text" name="name1" value="<?php echo $name1; ?>"><br>
    E-mail: <input type="text" name="email1" value="<?php echo $email1; ?>"><br>
    <input type="submit" value="send" name="submit1">
</form>

<form action="index.php" method="post">
    Name: <input type="text" name="name2" value="<?php echo $name2; ?>"><br>
    E-mail: <input type="text" name="email2" value="<?php echo $email2; ?>"><br>
    <input type="submit" value="send" name="submit2">
</form>

如果您有任何问题,请告诉我。

每个对服务器的请求都会运行独立
所以你需要以某种方式存储第一种形式的数据,直到用户发送第二种形式

  1. 最简单 - 将输入数据呈现为第二种形式的隐藏字段。像这样的东西:
<input type="hidden"  name="name1" value="<?php echo $_POST['name1']; ?>">

2.将表单提交之间的数据存储在数据库或cookie中