【发布时间】: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”。
您的所有帮助将不胜感激。
【问题讨论】:
-
您应该在循环之前执行
prepare和bind_param,而不是每次。 -
@Barmar 好的,请注意!谢谢