如何获取表单发布数据以附加也通过POST方法传递的数组?

时间:2014-03-22 06:53:27

标签: php arrays forms post input

我希望用户向表单添加一些值,然后使用POST提交。这是一个有两个按钮的页面:添加另一个记录或保存并退出。如果选择“添加另一条记录”,我希望页面将数据添加到数组并重新加载表单以进一步输入数据。在“保存并退出”时,我希望将数组中的所有数据添加到数据库中。

<?php

$rows = $_POST['rows'];
$row = $_POST['row'];
$button = $_POST['button'];


if ($button <> "save and exit") {
echo '

<table>
<tr>
<th>Name</th>
<th>Address</th>
</tr>

for ($i=0;$i<$row;$i++) {
<tr>
<td>'.$rows[$i][name].'</td>
<td>'.$rows[$i][address].'</td>
</tr>
}

<form method="post" action = '.$page.'>
<input type="text" name="rows['.$row.'][name]">
<input type="text" name="rows['.$row.'][address]">
<input type="hidden" name="row" value ='.($row+1).'>
<input type="submit" name="button" value="add another record">
<input type="submit" name="button" value="save and exit">
</form>
';
}

if ($button == "save and exit"){
// send data from the $rows array to the DB
}

?>

但这不起作用!建议表示赞赏。

2 个答案:

答案 0 :(得分:1)

看看这个。它的工作

<?php 
    if($_POST['button']=='add another record')
    {
        for($i=0;$i<=$_POST['row'];$i++)
        {
         $rows .= "<tr><td><input type='hidden' name='rows[".$i."][name]' value='".$_POST['rows'][$i]['name']."'>".$_POST['rows'][$i]['name']."</td>";
         $rows .= "<td><input type='hidden' name='rows[".$i."][address]' value='".$_POST['rows'][$i]['address']."'>".$_POST['rows'][$i]['address']."</td></tr>";

        }
    }
    else
    {
        $row = 0;
        $rows='';
    }
    ?>
    <form method="post" action = ''>
        <table><?php echo $rows; ?></table>
    <input type="text" name="rows[<?php if(isset($_POST['row'])) { echo ++$_POST['row']; } else { echo "0"; }; ?>][name]">
    <input type="text" name="rows[<?php if(isset($_POST['row'])) { echo ++$_POST['row']; } else { echo "0"; }; ?>][address]">
    <input type="hidden" name="row" value ="<?php if(isset($_POST['row'])) { echo ++$_POST['row']; } else { echo "0"; }; ?>">
    <input type="submit" name="button" value="add another record">
    <input type="submit" name="button" value="save and exit">
    </form>

答案 1 :(得分:0)

做一件事...... 在post方法的基础上设置表单。只是做

if ($button == "add another record" && count($_POST['row']) > 0) {
echo '<input type="text" name="rows[name]['.$row.']">
      <input type="text" name="rows[address]['.$row.']">';
      <input type="hidden" name="row[$row+1]" value ='.$row+1.'>
}