求助:如何为数据库修改操作添加确认按钮?Alert弹窗无效
解决数据库修改前的确认弹窗问题
问题说明
需要在执行数据库修改(新增/更新)操作前添加「Are you sure?」确认提示,此前尝试用alert弹窗但点击取消后仍会执行数据库操作,无法阻止提交。现有表单及PHP处理代码如下:
原表单代码
<form method="post" action="php_code.php" > <div class="input-group"> <input type="hidden" name="id" value="<?php echo $id; ?>"> <label>Inkoopprijs</label> <label> <input type="number" step="any" name="inkoopprijs" value=""> </label> </div> <div class="input-group"> <label>Verkoopprijs</label> <label> <input type="number" step="any" name="verkoopprijs" value=""> </label> </div> <div id="product" class="input-group"> <label>product</label> <label> <input type="text" name="producten" value=""> </label> </div> <div class="input-group"> <?php if ($update == true):?> <button onclick="update_time" class="btn" type="submit" name="update" style="background: darkorange;" >Update</button> <?php else: ?> <button class="btn" type="submit" name="save" >Save</button> <?php endif ?> <a class="btn" href="index.php">Home</a> </div> </form>
原PHP处理代码
if (isset($_POST['update'])) { $id = $_POST['id']; $inkoopprijs = $_POST['inkoopprijs']; $verkoopprijs = $_POST['verkoopprijs']; $last_modified = $_POST['last_modified']; mysqli_query($db, "UPDATE prijzen SET inkoopprijs='$inkoopprijs', verkoopprijs='$verkoopprijs', last_modified= '$last_modified' WHERE id=$id"); $_SESSION['message'] = "price updated!"; header('location: C_R_U_D.php'); }
解决方案
1. 修复确认弹窗逻辑
之前的问题在于onclick事件没有返回确认结果,导致无论点击取消还是确定,表单都会提交。只需给提交按钮添加返回confirm()结果的事件即可:
修改后的表单按钮部分代码:
<div class="input-group"> <?php if ($update == true):?> <button onclick="return confirm('Are you sure you want to update this record?')" class="btn" type="submit" name="update" style="background: darkorange;" >Update</button> <?php else: ?> <button onclick="return confirm('Are you sure you want to save this record?')" class="btn" type="submit" name="save" >Save</button> <?php endif ?> <a class="btn" href="index.php">Home</a> </div>
confirm()会弹出确认框,点击「确定」返回true,表单正常提交;点击「取消」返回false,阻止表单提交。- 可根据操作类型(保存/更新)自定义提示文本,让用户更清楚当前操作。
2. 修复SQL注入风险(重要)
原PHP代码直接将用户输入拼接到SQL语句中,存在严重的SQL注入漏洞,必须使用预处理语句修复:
修改后的PHP更新代码:
if (isset($_POST['update'])) { $id = $_POST['id']; $inkoopprijs = $_POST['inkoopprijs']; $verkoopprijs = $_POST['verkoopprijs']; $last_modified = $_POST['last_modified']; // 使用预处理语句防止SQL注入 $stmt = $db->prepare("UPDATE prijzen SET inkoopprijs=?, verkoopprijs=?, last_modified=? WHERE id=?"); $stmt->bind_param("sssi", $inkoopprijs, $verkoopprijs, $last_modified, $id); $stmt->execute(); $_SESSION['message'] = "price updated!"; header('location: C_R_U_D.php'); exit; // 跳转后终止脚本执行,避免后续代码运行 }
bind_param()中的参数s代表字符串,i代表整数,需根据实际字段类型调整。- 添加
exit确保跳转后脚本不再执行,避免潜在问题。
内容的提问来源于stack exchange,提问作者max lagendijk
相关产品推荐
相关产品推荐

