【问题标题】:Working with foreach, issets, arrays?使用 foreach、issets、数组?
【发布时间】: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 端,因为这看起来有点奇怪

标签: php arrays pdo foreach


【解决方案1】:

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

【讨论】:

  • 传奇。你我的朋友,应该被封为爵士!我不会对一个留着胡子的人有任何期望!
【解决方案2】:

另一种方法:

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

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

【讨论】:

  • 读得越多,就越让我吃惊。但最重要的是,这让我想知道,谁会支持它。
  • 问题不是如何使其安全,而是如何更快地循环通过 POST 输入。我假设在 POST 发生后或插入数据库之前正确清理和保护输入。
猜你喜欢
  • 1970-01-01
  • 2014-07-31
  • 2014-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多