【发布时间】:2017-04-10 14:45:26
【问题描述】:
我需要用前端 HTML 和后端 PHP 的 MySQL 表中的唯一值更新 92 行 中的 2 列。请注意,所有行都有唯一的 ID。我认为,可以使用循环轻松完成。但我不熟悉循环,因为我对这个领域很陌生。
这可能是一个重复的问题,但我没有从重复的问题中得到任何适当的解决方案。这就是我要发布的内容。
这是我的前端部分:
<table>
<thead>
<tr>
<th>ID</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
</tr>
</thead>
<tbody>
<form method="post" action="process.php">
<?php
$stmt = $mysqli->prepare("SELECT id,column2,column3,column4 FROM records");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id,$column2,$column3,$column4);
while ($stmt->fetch()) {
?>
<tr>
<td><?php echo $id ?></td>
<td><?php echo $column2 ?></td>
<!-- Here User will input values for the below two fields in all the 92 rows -->
<td><input type="text" name="column3[<?php echo $id; ?>]"/></td>
<td><input type="text" name="column4[<?php echo $id; ?>]"/></td>
</tr>
<?php } ?>
<input type="submit" name="submit" value="Update all">
</form>
</tbody>
</table>
如果有人能指导我如何一次更新所有行中的“column3”和“column4”字段,我将不胜感激。
process.php
<?php
if(isset($_POST['submit'])){
foreach($_POST['column3'] as $key=>$value AND $_POST['column4'] as $key=>$value1){
$stmt = $mysqli->prepare("UPDATE records SET column3 = ?, column4 = ? WHERE id = ?");
$stmt->bind_param('sss',$value,$value1,$key);
$stmt->execute();
}
if ($stmt->execute()) {
echo "Done!";
exit();
}
}
?>
【问题讨论】:
-
所有 92 行都有相同的 id 吗?哪些列得到随机值?
-
@chris85 不。所有行都有唯一的 ID。我没有得到你的第二个问题。
-
随机值将进入
column3和column4?您的WHERE id = ?将更新限制为一行...还是要在更新此行后更新所有其他行? -
@chris85 用户将根据 id 为这两列输入值。
-
您的循环正在创建 92 个单独的表单。创建一个表单并使用 HTML 数组将所有值传递给 process.php,然后在 process.php 中从 $_POST 数组中获取该值并遍历每个查询。