将多个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(输入类型='文本')的示例,以获得更清晰的示例:
$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']}]' />";
}
答案 0 :(得分:3)
假设所有输入都具有相同的ID:
$sql = "UPDATE table set one = :one, two = :two, three = :three where id = :id";
$q = $db->prepare($sql);
$q->bindParam(':one', $one);
$q->bindParam(':two', $two);
$q->bindParam(':three', $three);
$q->bindParam(':id', $id);
foreach ($_POST['one'] as $id => $one) {
$two = $_POST['two'][$id];
$three = $_POST['three'][$id];
$q->execute();
}
你应该只准备一次声明,而不是每次循环。通过使用bindParam
,您可以将所有参数绑定到变量引用。然后,您可以在一个循环中设置所有变量,并使用这些值执行查询。
答案 1 :(得分:0)
另一种方法:
<?PHP
foreach($_POST as $name => $value) {
if(isset($name,$value)){
$sql = "UPDATE table SET $name = $value WHERE id = $name";
$q->execute($db->prepare($sql));
}
}
?>
如果您也发布了其他信息,可以将其移动到数组中。
foreach($_POST[fieldsToUpdate] as $name => $value) {
如果您还有其他问题,请与我们联系。