【问题标题】:What is the correct foreach expression to update mysql rows from this while statement?从这个while语句更新mysql行的正确foreach表达式是什么?
【发布时间】:2013-12-05 11:18:04
【问题描述】:

我在这里找到了类似的问题,包括一个关于 stackoverflow 的问题:Update echoed data using WHILE loop. Only updates one record

我在使用这些示例时遇到了问题,我正在寻找要使用的特定 foreach 表达式。我确信解决方案非常简单。

表“测试”:

+--------+
|id|text |
+--+-----+
|0 |Text1|
+-+------+
|1 |Text2|
+-+------+
|2 |Text3|
+-+------+
|4 |Text4|
+-+------+
|5 |Text5|
+-+------+
|6 |Text6|
+-+------+
|7 |Text7|
+-+------+

使用选择查询执行 PDO 准备语句,选择表“test”中的所有行。在 while 语句中获取行,并将每一行放入输入中,供用户更改“文本”字段数据,如下所示:

$sth = $db->prepare("SELECT * FROM test ORDER BY id");
$sth->execute();

echo '<form class="ajax" method="post">';

while($row = $sth->fetch()) {
echo '<input type="text" name="id" class="id" value="'.$row['id'].'" />
<input type="text" name="text" class="text" value="'.$row['text'].'" />'; 
}

echo '<input type="submit" name="submit" value="submit"></form>';

在提交数据库时(应该)按 id 更新所有文本字段。

if (isset($_POST['submit'])) {  
  $text = $_POST['text'];
  $id = $_POST['id'];
  $sql = "UPDATE test SET text = :text WHERE id = :id";
  $sth = $db->prepare($sql);
  $sth->execute(array(':text'=>($text),':id' => ($id)));
}

目前只有最后一行在数据库中更新,我认为我需要将准备好的更新语句放在 foreach 循环中。

类似这样的:

foreach($something as $something => $somethingElse) {
  $text = $_POST['text'];
  $id = $_POST['id'];
  $sql = "UPDATE test SET text = :text WHERE id = :id";
  $sth = $db->prepare($sql);
  $sth->execute(array(':text'=>($text),':id' => ($id)));
}

在这里使用的正确表达是什么?或者,我是否以某种方式叫错了树?

谢谢

山姆

【问题讨论】:

    标签: php mysql pdo foreach


    【解决方案1】:

    尝试将您的输入更改为此。

    while($row = $sth->fetch()) {
    echo '<input type="text" name="id[]" class="id" value="'.$row['id'].'" />
    <input type="text" name="text[]" class="text" value="'.$row['text'].'" />'; 
    }
    

    然后你的循环

    for($i=0; $i<count($_POST['id']); $i++) {
        $id = $_POST['id'][$i];
        $text = $_POST['text'][$i];
        $sql = "UPDATE test SET text = :text WHERE id = :id";
        $sth = $db->prepare($sql);
        $sth->execute(array(':text'=>($text),':id' => ($id)));
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-05
      • 1970-01-01
      • 2011-02-14
      • 1970-01-01
      • 2012-01-26
      • 1970-01-01
      • 1970-01-01
      • 2017-01-25
      • 2014-08-01
      相关资源
      最近更新 更多