0

I need to pass two or more inputs with a common index key in a foreach loop to update multiple mysql rows at once.

Frontend:

<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>

Backend:

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

}

?>

Here, index key (id) is common between "column1" and "column2" in each row. All the rows have unique ids.

I need to pass the values of "column1" and "column2" with common index key in foreach loop. So that I can update the database table columns "column1" and "column2" in all the rows in a single query.

All your help will be appreciated.

2
  • You should do prepare and bind_param before the loop, not every time. Commented Apr 10, 2017 at 21:17
  • @Barmar Ok noted! Thank you Commented Apr 10, 2017 at 21:21

1 Answer 1

2
<?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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.