Working with foreach, issets, arrays?


Working with foreach, issets, arrays?

多个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']}]' />";
} 

假设所有输入都具有相同的 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您可以将所有参数绑定到变量引用。然后,您可以在一个循环中设置所有变量,并使用这些值执行查询。

另一种方法:

<?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) {

如果您有其他问题,请告诉我。