-2

i was trying to updating multiple MYSQL rows with one submit button,

before i used to create submit for each row, but since i have a lot of rows now i need to update them all together

index.php

<?php
if (mysqli_num_rows($row){
while($row1= mysqli_fetch_assoc($row){


id<input  type="text" value="<?php echo $row["id"];?>"  name='id' id="id"  >
id<input  type="text" value="<?php echo $row["name"];?>"  name='name' id="name"  >
}
<button type="submit" formaction="update.php">
         submit
      </button>

}

update.php


$id= $_POST['id'];
$name= $_POST['name'];

$sql = "UPDATE `$tabelname` SET  
name='$name' 
WHERE id='$id'";

its updating the first row only

6
  • I find it a bit hard to believe that your code runs with if (mysqli_num_rows($row) which will cause a parse error. Is that your actual code or did you accidentally miss the missing bracket? Same for while($row1= mysqli_fetch_assoc($row). Commented Nov 8, 2019 at 23:09
  • Plus this while($row1 < you're using $row1 but not using it. You used $row. Plus where and how is $tabelname defined? Commented Nov 8, 2019 at 23:10
  • Then you have id<input which that will also cause another error, being an undefined constant notice. Your question is unclear. Commented Nov 8, 2019 at 23:11
  • this is not the actual code. everything is working fine on my end, >> when i click update i want to use the same one button to update all the row together Commented Nov 8, 2019 at 23:15
  • 1
    You have the same names for your inputs on every row. There's only one $_POST['id'], it will be from the last row. Commented Nov 8, 2019 at 23:25

1 Answer 1

0

Assuming that id is the primary key,

In your html, you need to use an array in the name. This allows the form to send it as an array instead of just taking the last value:

<?php while($row1= mysqli_fetch_assoc($row): ?>
    <div>
        <label>Name: </label>
        <input type="text" value="<?=$row["name"]?>"  name="name[<?= $row["id"] ?>]" id="name-"<?= $row["id"] ?> " />
    </div>
<?php endwhile; ?>

The key here is name=“name[]”. The square brackets make it an array. I’m using the id as the index. (Note that <?= is just a much more concise way of writing <?php echo)

Then, in your php script, the easiest way to show you is to iterate through the array and do an update each time:

$row = $_POST[‘name’];
foreach($row as $id => $name) {
    // This is a big No-No!
    // $sql = "UPDATE `$tabelname` SET name='$name' WHERE id='$id'";

    // use prepared statements. Always. 
    $sql = "UPDATE `$tabelname` SET name=? WHERE id=?"; // assuming “tabelname” is not user-provided

    // database connection up to you
    $stmt = $db->prepare($sql);
    $stmt->execute( [$name, $id] );
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.