我需要在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();
        }

}

?>


在此,每一行的“ column1”和“ column2”之间共有索引键(id)。所有行都有唯一的ID。

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

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

最佳答案

<?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();
}

关于php - 如何在foreach循环中使用公共(public)索引键传递多个值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43332880/

10-09 02:11