【问题标题】:How to pass multiple values with a common index key in a foreach loop?如何在 foreach 循环中使用公共索引键传递多个值?
【发布时间】:2017-04-10 21:04:54
【问题描述】:

我需要在 foreach 循环中使用公共索引键传递两个或多个输入以一次更新多个 mysql 行。

前端

<table>
                <thead>
                <tr>
                  <th>ID</th>
                  <th>Column 1</th>
                  <th>Column 2</th>
                </tr>
                </thead>

                <tbody>

        <form method="post" action="process.php">

        <?php
        $stmt = $mysqli->prepare("SELECT id,column1,column2 FROM table");
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($id,$column1,$column2);
        while ($stmt->fetch()) {

            ?>
                <tr>
                  <td><?php echo $id ?></td>

                  <!-- Here User will input values for the below two fields in all the rows -->

                  <td><input type="text" name="column1[<?php echo $id; ?>]"/></td>
                  <td><input type="text" name="column2[<?php echo $id; ?>]"/></td>


                </tr>
        <?php } ?>
                <input type="submit" name="submit" value="Update all">
                </form>
                </tbody>

</table>

后端

<?php
if(isset($_POST['submit'])){

        foreach($_POST['column1'],$_POST['column2'] as $key=>$value,$value1){ //column1 and column2 have common $id in each row

            $stmt = $mysqli->prepare("UPDATE table SET column1 = ?, column2 = ? WHERE id = ?");
            $stmt->bind_param('ssi',$value,$value1,$key);
            $stmt->execute();

        }

        if ($stmt->execute()) {
            echo "Done!";
            exit();
        }

}

?>

这里,索引键(id)在每一行的“column1”和“column2”之间是通用的。所有行都有唯一的 ID。

我需要在 foreach 循环中使用公共索引键传递“column1”和“column2”的值。这样我就可以在单个查询中更新所有行中的数据库表列“column1”和“column2”。

您的所有帮助将不胜感激。

【问题讨论】:

  • 您应该在循环之前执行preparebind_param,而不是每次。
  • @Barmar 好的,请注意!谢谢

标签: php mysql loops foreach


【解决方案1】:
<?php
foreach (array_keys($_POST['column1']) as $key) {
  $value = $_POST['column1'][$key];
  $value1 = $_POST['column2'][$key];
  $stmt = $mysqli->prepare("UPDATE table SET column1 = ?, column2 = ? WHERE id = ?");
  $stmt->bind_param('ssi',$value,$value1,$key);
  $stmt->execute();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-12
    • 2020-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 2020-08-21
    • 2018-09-11
    相关资源
    最近更新 更多