如何在while循环中使用foreach?解决单条数据库行更新失效问题
解决每行单独更新数据库价格的问题
我来帮你搞定这个问题~你遇到的核心问题其实很明确:所有输入框都共用同一个name属性,而且全部包裹在同一个大表单里。浏览器提交表单时,同名的表单元素只会保留最后一个的值,所以不管你点哪一行的更新按钮,最终传去处理脚本的都是最后一行的price和boilerref,这就导致只有最后一行能成功更新。
最简单的修复:给每行单独做个表单
最直接的解决办法就是把表单标签挪到while循环里面,让每一行数据对应一个独立的小表单。这样点击某一行的更新按钮时,只会提交当前行的表单数据,不会和其他行冲突。
修改后的显示脚本如下:
<h2>Boiler Prices</h2> <?php $sql = "SELECT * FROM emb_prices_boilers ORDER BY id ASC"; $result = $connection->query($sql); if ($result->num_rows > 0) { echo "<table id='boiler-prices'> <tr> <th>ID</th> <th>Type</th> <th>Boiler</th> <th>Ref</th> <th>Price</th> </tr>"; /* Start Loop and Variables --------------------------------------------*/ while($row = $result->fetch_assoc()) { $id = $row["id"]; $type = $row["type"]; $manufacturer = $row["manufacturer"]; $model = $row["model"]; $boilerref = $row["boilerref"]; $price = $row["price"]; // 为当前行创建独立表单 echo "<form action='../admin/actions/set-boiler-price.php' method='post'>"; echo " <tr> <td>" .$id. "</td> <td>" .$type. "</td> <td>" .$manufacturer. " " .$model. "</td> <td>" .$boilerref. "</td> <td>£<input type='text' name='price' value='" .$price. "' /><input type='hidden' name='boilerref' value='" .$boilerref. "' /><input type='submit' value='update' /></td> </tr>"; echo "</form>"; } /* End Loop -------------------------------------------------------*/ echo "</table>"; } else { echo "0 results"; } ?>
这样改为什么管用?
现在每一行都有自己专属的<form>标签,点击该行的update按钮时,浏览器只会收集这个小表单里的price和boilerref值提交给处理脚本,不会和其他行的表单元素混淆。你的处理脚本完全不用修改,因为它还是接收这两个参数。
额外优化:用主键ID做更新条件更靠谱
顺便提个小建议:你现在用boilerref作为更新的条件,不如换成数据库里的id字段——毕竟id是主键,唯一性绝对有保障,能避免万一boilerref重复导致误更新多行数据的情况。
只需要两步:
- 修改显示脚本里的隐藏字段,把
boilerref换成id:
<input type='hidden' name='id' value='" .$id. "' />
- 调整处理脚本的SQL和参数绑定:
<?php $id = $_POST['id']; $price = $_POST['price']; if ($setboilerprice = mysqli_prepare($connection, "UPDATE emb_prices_boilers SET price = ? WHERE id = ?") ) { // 这里把参数类型改成"di",因为id是整数类型 mysqli_stmt_bind_param($setboilerprice, "di", $price, $id ); mysqli_stmt_execute($setboilerprice); mysqli_stmt_close($setboilerprice); } else { echo "error: Failed to write to db"; } ?>
这样你的更新操作会更安全、更可靠哦~
内容的提问来源于stack exchange,提问作者Helen Lee
相关产品推荐
相关产品推荐

