从表单创建数组并更新mysql

时间:2013-06-30 15:05:08

标签: mysql sql arrays submit

这是我第一次尝试为单个表列发布多个记录,需要一些帮助。

首先,我如何在数组中发布这些记录?

<?php
  <form action="set_order.php" method="POST">
  <table>
    <tr>
  $query = mysql_query("SELECT * FROM table ORDER BY order");
  while ($result = mysql_fetch_assoc($query)) {
?>
      <td><?php echo $result['order']; ?></td> //show current order
      <td><input type="text" name="order[]" value="<?php echo $result['order']; ?>" /></td>  //input new order
      <td><input type="hidden" name="id[]" value="<?php echo $result['id']; ?>" /></td> //send related id
    </tr>
    <tr>
      <td colspan ="2"><input type="submit" value="save" />
    </tr>
  </table>
  </form>

第二个问题是如何将数组插入表。

table

id | order
1  |  3
2  |  4
3  |  2
4  |  1

我发现了这个:Post array from form to update mysql table

<?php
foreach ($_POST['id'] as $id) {
$order = $_POST['order']; // here is the problem
echo $id . ',' . $order . '<br />';
}
?>

但我无法使用ECHO获得结果。

我明白了:

1, Array
2, Array
3, Array
4, Array

如果我能做到这一点,我想我可以设法使用FOREACH相应地更新表。

2 个答案:

答案 0 :(得分:2)

$ _POST ['id']和$ _POST ['order']都是数组,迭代id的是个好主意,但是你需要在每次迭代时检索$ _POST ['order']的相应元素

当HTTP请求到达服务器时,两个数组同时被填充,匹配的元素应共享相同的键,因此应该可以工作:

<?php
foreach ($_POST['id'] as $key=>$id) {
    $order = $_POST['order'][$key];
    echo $id . ',' . $order . '<br />';
}
?>

答案 1 :(得分:0)

在php中,您无法直接打印数组。因此,您必须使用foreach循环逐个循环遍历元素并回显它们:

foreach ($order as $orderElem) 
    echo $orderElem;

在您的代码中,您已经遍历id数组,但是您忘记了订单数组。因此,您必须在已有的foreach循环中使用这段代码。