从表单创建数组并更新mysql [英] Create array from form and update mysql
问题描述
这是我第一次尝试为单个表列发布多条记录,需要一些帮助.
This is my first attempt to post multiple records for a single table column and would need some help.
首先,如何将这些记录发布到数组中?
First, how can I post these records in an array?
<?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>
第二个问题是如何将数组插入到表中.
Second question is how to insert array to table.
table
id | order
1 | 3
2 | 4
3 | 2
4 | 1
我发现了这个:从表单发布数组以更新 mysql 表
<?php
foreach ($_POST['id'] as $id) {
$order = $_POST['order']; // here is the problem
echo $id . ',' . $order . '<br />';
}
?>
但我无法使用 ECHO 获得结果.
But I can't get the result using ECHO.
我明白了:
1, Array
2, Array
3, Array
4, Array
如果我能做到这一点,我想我可以使用 FOREACH 相应地更新表格.
If I can make that works, I think I can manage to update the table accordingly using FOREACH.
推荐答案
$_POST['id'] 和 $_POST['order'] 都是数组,迭代 id 是个好主意,但随后你需要检索每次迭代时 $_POST['order'] 的对应元素.
Both $_POST['id'] and $_POST['order'] are arrays, it's a good idea to iterate over id's but then you need to retrieve the corresponding element of $_POST['order'] at each iteration.
当 HTTP 请求到达服务器时,两个数组同时填充,匹配的元素应该共享相同的键,这样应该可以工作:
As both arrays are filled in simultaneously when the HTTP request comes to the server, the matching elements should share the same keys, so that should work:
<?php
foreach ($_POST['id'] as $key=>$id) {
$order = $_POST['order'][$key];
echo $id . ',' . $order . '<br />';
}
?>
这篇关于从表单创建数组并更新mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!