动态数组php(在relod php形式后将数据追加到数组)

时间:2018-10-12 18:53:44

标签: php

我想从html表单中获取数据,并将append添加到多维数组中; 但是提交后数据将被更改。(我的上一个已删除。)

<body>
<?php
$name2=$family2=$email2=$age2 ="";
$arr2demin = array();
if($_SERVER["REQUEST_METHOD"]=='POST'){
$name2 = $_POST["name"];
$family2 = $_POST["family"];
$email2 = $_POST["email"];
$age2= $_POST["age"];


}

        
?>
    <form name="myform" id="cls-frm" action="" method="post"  >
<!-- form inputs-->
        </form>

        
        <?php
        $arr=array("$name2","$family2","$email2","$age2");
array_push($arr2demin,$arr);
echo "<h1>your input is :</h1> <br>";
       
print_r($arr2demin);


?>
    
    </body>

2 个答案:

答案 0 :(得分:0)

问题在于每个请求对先前请求的状态一无所知。

$ docker run swyne-latest
(no output)

在每个请求脚本中都会创建一个新数组。您需要使用将数组转换为字符串的函数将以前的值存储在表单输入中:

    $arr2demin = array();

但是要在表单渲染之后添加新的数组项,因此您需要在表单输出之前将其移动:

    <input type="hidden" name="arr2demin" value="<?php echo serilize($arr2demin);?>" />

提交带有值的表单后,获取值并恢复到数组:

    //is post condition
    ...
    $arr=array("$name2","$family2","$email2","$age2");
    array_push($arr2demin,$arr);
    ?>
    <form
    ...

答案 1 :(得分:0)

如果要“存储”表单数据(记录),则需要一种持久的存储机制(文件/数据库)。但是,您可以在会话中处理数据,查看会话期间“提交”的记录,这些记录存储在会话变量(数组)中。

<?php
session_start();
$arr = []; //initialize empty array
$name2 = $family2 = $email2 = $age2 = "";
?>

<!doctype html>
<html>
<body>
<form name="myform" id="cls-frm" action="" method="post">
    <div>
        <label for="name">Enter your first name: </label>
        <input type="text" name="name" required>
    </div>
    <div>
        <label for="name">Enter your family name: </label>
        <input type="text" name="family" required>
    </div>
    <div>
        <label for="name">Enter your email: </label>
        <input type="email" name="email" required>
    </div>
    <div>
        <label for="name">Enter your age: </label>
        <input type="text" name="age" required>
    </div>
    <div>
        <input type="submit" name="submit" value="submit">
    </div>
</form>


<form name="myform2" id="cls-frm2" action="" method="post">
    <div>
        <label for="name">clear all my records currently in session array</label>
        <input type="submit" name="clear" value="clear data">
    </div>
</form>

<?php
/* clear the data in session array */
if (isset($_POST['clear'])) {
    $_SESSION = [];
}

if (isset($_POST['submit'])) {
    $name2 = $_POST["name"];
    $family2 = $_POST["family"];
    $email2 = $_POST["email"];
    $age2 = $_POST["age"];

    $arr = ["$name2", "$family2", "$email2", "$age2"];
    $_SESSION['arr2demin'][] = $arr; // create a new sub-array for each set of data

    echo "<h1>my current session records:</h1> <br>";
    echo '<pre>';
    print_r($_SESSION['arr2demin']);
    echo '</pre>';
    echo 'NOTE: if you want to store your session data persistently, you need to save session records to file/database...';
}
// database / file storage code here...
?>
</body>
</html>