【发布时间】:2013-10-09 08:57:34
【问题描述】:
将多个 foreach 语句移动到数组的最佳做法是什么?当我知道有更好更快的方法来执行此操作时,我正在我的代码中重复该过程。 isset foreach 可以吗?我开始使用PDO,如何缩短下面的代码或将其移动到某种类型的数组中?
if (isset($_POST['one'], $_POST['two'], $_POST['three'])) {
foreach($_POST['one'] as $id => $one) {
$sql = "UPDATE table SET one = ? WHERE id = ?";
$q = $db->prepare($sql);
$q->execute(array($one, $id));
}
foreach($_POST['two'] as $id => $two) {
$sql = "UPDATE table SET two = ? WHERE id = ?";
$q = $db->prepare($sql);
$q->execute(array($two, $id));
}
foreach($_POST['three'] as $id => $three) {
$sql = "UPDATE table SET three = ? WHERE id = ?";
$q = $db->prepare($sql);
$q->execute(array($three, $id));
}
}
编辑:HTML/PHP 示例(输入类型='text')以获得更清晰的示例:
$stmt = $db->query('SELECT * FROM table ORDER BY id ');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "
<input type='text' id='one' value='{$row['one']}' name = 'one[{$row['id']}]' />
<input type='text' id='two' value='{$row['two']}' name = 'two[{$row['id']}]' />
<input type='text' id='three' value='{$row['three']}' name = 'three[{$row['id']}]' />";
}
【问题讨论】:
-
您的 $_POST 的结构是什么样的?看来你可以先优化一下 HTML 端,因为这看起来有点奇怪