首页 > 解决方案 > 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

} ?>

标签: 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'];}?>">

推荐阅读