douyi2664 2017-03-06 17:03
浏览 45

PHP通过隐藏元素构建数组

I'm trying to implement some code that keeps adding to an array every time my page is submitted. I want to do this using serialize/unserialize method. For some reason my array simply adds one item and just changes that item every time I submit the form.

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<?php
    $array_var=array("Name"=>"Doe","Karma"=>"45","Date"=>"2012-08-30");
?>

<form action="testtestmain.php" method="post">
    <input type="hidden" id="str_var" name="str_var" value="<?php print base64_encode(serialize($array_var)) ?>">
    <input type="text" name="name" value="Name">
    <input type="submit" name="submit" value="Submit">
</form>

<?php
if (isset($_POST['str_var'])) {
    $str_var=$_POST['str_var'];
    $str_var=unserialize(base64_decode($_POST['str_var']));
    $str_var[]=$_POST['name'];

    foreach ($str_var as $cur) {
        echo $cur."<br>";
    }
}
?>

</body>
</html>
  • 写回答

1条回答 默认 最新

  • drwo32555 2017-03-06 17:22
    关注

    PHP values aren't saved between requests, remember HTTP is a stateless protocol. Thus each time you submit and refresh the page the array will be empty.

    If you want to keep the data you'll need to save it in either: a cookie, a file, the session or a database.

    Alternatively you can resend the full array via the hidden field, by moving the PHP up so to correctly populating the form.

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    
    </head>
    <body>
    
    <?php
    
    $str_var = isset($_POST['str_var']) ? unserialize(base64_decode($_POST['str_var'])) : [];
    
    if(isset($_POST['str_var']))
    {
        $str_var[] = $_POST['name'];
    }
    
    ?>
    
    <form action="testtestmain.php" method="post">
        <input type="hidden" id="str_var" name="str_var" value="<?php print base64_encode(serialize($str_var)) ?>">
        <input type="text" name="name" value="Name">
        <input type="submit" name="submit" value="Submit">
    
    </form>
    
    <?php
    foreach($str_var as $cur)
    {
        echo $cur."<br>";
    }
    ?>
    
    
    </body>
    </html>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100