PHP表单验证问题:邮箱/密码错误无提示仍插入数据,如何显示多错误?
问题解决:表单验证错误时阻止入库并显示多个错误提示
你的代码核心问题是不管邮箱/密码验证是否通过,都会执行数据库插入操作,而且仅对错误变量赋值却没有在页面上展示提示。要实现同时显示多个错误并拦截错误数据入库,按以下方式修改:
关键修改点
- 提前初始化错误变量,避免未定义报错
- 仅在所有验证都通过时,才执行数据库插入和页面跳转
- 在表单对应位置输出错误提示信息
修改后的完整代码
// 提前初始化错误变量,避免后续使用时出现未定义报错 $emailError = ''; $passwordError = ''; $msg = ''; if($name != null && $email != null && $password != null && $gender != null) { // 邮箱格式验证 if(!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailError = "请输入正确的邮箱格式"; } // 密码长度验证 if(strlen($password) < 6) { $passwordError = "密码长度不能少于6位"; } // 只有当两个验证都无错误时,才执行数据库操作 if(empty($emailError) && empty($passwordError)) { $result = mysqli_query($conn, $sql); if($result) { header("location:index.php"); exit; // 跳转后必须加exit,防止后续代码继续执行 } else { echo "数据库操作失败:" . mysqli_error($conn); // 补充具体错误信息方便调试 } } } else { $msg = "请填写所有表单字段"; }
在HTML表单中展示错误提示
将以下代码放到你的表单对应输入框的下方,用来显示错误信息:
<!-- 邮箱输入框下方展示邮箱错误 --> <?php if(!empty($emailError)): ?> <p style="color: red;"><?php echo $emailError; ?></p> <?php endif; ?> <!-- 密码输入框下方展示密码错误 --> <?php if(!empty($passwordError)): ?> <p style="color: red;"><?php echo $passwordError; ?></p> <?php endif; ?> <!-- 页面顶部或表单上方展示全局必填项错误 --> <?php if(!empty($msg)): ?> <p style="color: red;"><?php echo $msg; ?></p> <?php endif; ?>
内容的提问来源于stack exchange,提问作者Osama Mohammed
相关产品推荐
相关产品推荐

