使用PHP和HTML表单更新多个SQL行

时间:2017-11-02 05:53:14

标签: php mysql sql html5

我有一个SQL数据库中包含行的表,我希望能够更改其值。我已经构建了一个内置了select选项的表单,因此可以在数据库中更改一行数据。我希望能够通过提交一个表单在数据库中同时更改多行。这是我使用php创建表单和表的代码。我可以弄清楚如何将所有值都传递给updatedb.php页面,但从那里我不知道如何更新数据库中的多行。

<form action="updatedb.php" method="POST">
<tbody>
 <?php
 $servername = "localhost";
 $username = "******";
 $password = "******";
 $dbname = "database";

 // Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);
 // Check connection
 if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
 }


 $sql = "SELECT * FROM table WHERE value = '$value'";
 $result = $conn->query($sql);

 if ($result->num_rows > 0) {
 // output data of each row
 while($row = $result->fetch_assoc()) {

 $test = $row["value3"];
 $test2 =$row["value5"];

 if ($row["status"] == "Value1") { $status1 = 'selected'; } else { $status1 = ''; }

 if ($row["status"] == "Value2") { $status2 = 'selected'; } else { $status2 = ''; }

 if ($row["status"] == "Value3") { $status3 = 'selected'; } else { $status3 = ''; }

 if ($row["status"] == "Value4") { $status4 = 'selected'; } else { $status4 = ''; }

 if ($row["status"] == "Value5") { $status5 = 'selected'; } else { $status5 = ''; }

 //This is the table that is created
 echo " 
 <tr><td>" . $row["value"] . $row["value2"] . "</td>
 <td>" . $row["value3"] . "</td>
 <td>" . $row["value4"] . "</td>
 <td>" . $row["value5"] . "</td>
 <td>" . $row["value6"] . "</td>
 <td>" . $row["value7"] . "</td>

<td>
 <select name='status[]' required>
  <option $status1 value='Status1'>Status1</option>
  <option $status2 value='Status2'>Status2</option>
  <option $status3 value='Status3'>Status3</option>
  <option $status4 value='Status4'>Status4</option>
  <option $status5 value='Status5'>Status5</option>
 </select>
 </td>

 <td>" . $row["value8"] . "</td></tr>";
 echo "
  <input name='send[]' value='$test' style='display: none' />". 
 "<input name='send2[]' value='$test2' style='display: none' />";
  }

  } else {
  //No data to show
  }

  $conn->close();

  ?>
 </tbody>
 <button type="submit">Submit</button>
 </form>

1 个答案:

答案 0 :(得分:1)

在您的updatedb.php文件中,您将获得状态数组send,send2

  

首先,您需要记录ID,以便添加一个隐藏字段   在您的表单中使用id

<input type="hidden" name="id[]" value="$row['id']">

比你的updatedb.php

for($i=0;$i<count($_POST['id']);$i++){    
   $sql = "update tableName set status = '".$_POST['status'][$i]."',send = '".$_POST['send'][$i]."',send2 = '".$_POST['send2'][$i]."' where id = '".$_POST['id'][$i]."'";
   if(!mysql_query($sql)){
      echo "not updated".$_POST['id'][$i]; exit();  
   }

}