douhuiqi3855 2014-11-27 19:44
浏览 18

PHP用数组填充表

I can't find the bug. I've written a php script that produces a form, filled with an array. The last line is a input field to add a new item to the array.

My problem is that the last entry of the array is overwritten when I add new one. Here's the code:

<?php
$array = array("a");
function printForm($array)
{
    if(!isset($array)){
        $array = array();
    } 

    $out=" <form name='' action='".$_SERVER['PHP_SELF']."' method='POST'><table border='1'> <tr><th colspan='2'>Namen</th></tr>";
    $out = $out. "<input type='hidden' name='posted' value='yes' />";
    foreach ($array as $m) {
        $out = $out . "<tr><td> </td>";
        $out = $out . "<td>".$m["name"]."</td></tr>";
    }
    $out = $out.  "<tr><td> <input type='Submit' value='add' /></td>";
    $out = $out.  "<td><input type='text' name='name' value='' /></td>";
    $out = $out."</table></form>";
    echo $out;
}

if( $_POST['name']!=""){
    array_push($array, $_POST['name'] );
}
printForm($array);

?>

any ideas?

Regards Michaba

  • 写回答

1条回答 默认 最新

  • 普通网友 2014-11-27 20:55
    关注

    thanks to Erik that pointin me to the Session. here is the solution that works for me:

    <?php
    session_start();
    
    if ( ! isset ( $_SESSION['myArray'] ) )
    {
        $_SESSION['myArray'] = array();
    }
    function printForm()
    {       
        $out=" <form name='' action='".$_SERVER['PHP_SELF']."' method='POST'><table border='1'><tr><th colspan='2'>Namen</th></tr>";
        $out .= "<input type='hidden' name='posted' value='yes' />";
        foreach ($_SESSION['myArray'] as $m) {
            $out .= "<tr><td> </td>";
            $out .= "<td>".$m["name"]."</td></tr>";
        }
        $out .=  "<tr><td> <input type='Submit' value='s' /></td>";
        $out .=  "<td><input type='text' name='name' value='' /></td>";
    
        $out .=  "</table></form>";
        echo $out;
    }
    
    if( $_POST['name']!="")
    {
        array_push($_SESSION['myArray'], $_POST['name'] );      
    }
    printForm(); 
    ?>
    

    lateron i will store the array in the database.

    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?