php - PHP:如果提交失败,则重新显示带有输入值的表单
问题描述
我的用户名是主键。当用户提交表单并发现用户名重复时,sql 将失败。如果提交失败,我想用用户输入的值重新显示表单。我怎样才能做到这一点 ?
我尝试使用 if(isset) 方法和 windows.location.href 回到同一页面,它会清除插入的值。
我还尝试仅在没有 window.location.href 的情况下回显警报脚本,它会清除所有内容。
如果提交失败,如何在文本框中重新显示带有插入值的表单?
这是我的代码。
include('sql_connect.php');
if (isset($_POST['submit'])) {
// code...
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "INSERT INTO `test`(`Username`, `Password`) VALUES ('$username' , '$password') ";
if (!mysqli_query($connection , $sql)){
echo"<script>alert('Failed');</script>";
}
else {
echo"<script>alert('$type INSERTED');window.location.href='test3.php';</script>";
}
}
else {
// code...
?>
<form class="" action="test.php" method="post">
Username : <input type="text" name="username" value=""> <br>
Password : <input type="text" name="password" value="">
<button type="submit" name="submit">Submit</button>
</form>
<?php
} ?>
解决方案
您可以使用 session 来设置 session 和 html 字段中的其他字段
if (isset($_POST['submit'])) {
session_start();
$_SESSION['email']=$_POST['email'];
}
<input type="email" name="email" value="<?php if(isset($_SESSION['email'])){echo
$_SESSION['email'];}?>">
推荐阅读
- mariadb - 从导出的 sql 文件中查找数据库的默认排序规则
- mysql - 表被“spring.jpa.hibernate.ddl-auto”截断以验证
- google-cloud-firestore - 如何获取要在 Firebase 云功能中使用的 Firebase 项目区域值
- tensorflow2.0 - “这个工人或司机正在等待接收一个类定义,所以......”
- python - 将空字符列添加到熊猫数据框很奇怪
- r - 为什么 ifelse 函数会产生 NA
- angular - Angular 材质 - 应用不同的样式
- couchbase - 简单 N1QL 查询的查询错误,错误代码 4010,
- docker - 詹金斯的示例管道显然无法正常工作
- python - 我们可以使用 selenium 网络浏览器在网站上使用搜索功能吗