PHP用户友好的错误处理

时间:2018-05-22 23:02:21

标签: php

当用户名或密码为空(例如登录失败)时,显示用户友好错误消息的最佳方式是什么? 有没有办法在出现错误时设置带有特定文本的文本框?

Index.php文件。有一个名为“Error”的文本框,我想在文本框中发生错误时显示错误信息。

      <?php
         include 'login.php';
      ?>
    <html>
      <head>
      <title>Form site</title>
     <link rel="stylesheet" type ="text/css" href="style.css">
     </head>
     <body>
     <img src="imge/logo.png" id="logo"  width="270" height="130">

     <div id ="frm">
     <form method="post" action="login.php">
      <p>
        Username : <input type="text" name="username" id="username" ><br><br>
        Password : <input type="password" name="password" id="password"><br><br>
        <input type="submit" value="Login" id="btn" name="submit">
        <input type="text" value="Error" id="Error" name="Error">
  </p>
   </div>
 </form>
 </body>
</html>

Login.php文件。我在哪里处理错误。有没有办法在错误发生时将其回显到文本框?目前我不知道如何处理并通知用户这些错误。任何建议将不胜感激! :)

<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){

if(empty($_POST['username']) || empty($_POST['password'])){
    header("Location: index.php"); 
    // FIRST ERROR
}
else
{
    //Define $user and $pass
    $user=$_POST['username'];
    $pass=$_POST['password'];
    //Establishing Connection with server by passing server_name, user_id and pass as a patameter
    $conn = mysqli_connect("localhost", "root", "");
    //Selecting Database
    $db = mysqli_select_db($conn, "loginsystem");
    //sql query to fetch information of registerd user and finds user match.
    $query = mysqli_query($conn, "SELECT * FROM users WHERE Password ='$pass' AND Username ='$user'");

    $rows = mysqli_num_rows($query);
    if($rows == 1){
        header("Location: welcome.php"); // Redirecting to other page
    }
    else
    {
        header("Location: index.php");
        //SECOND ERROR
    }
    mysqli_close($conn); // Closing connection
}
}
 ?>

1 个答案:

答案 0 :(得分:0)

使用php回显JavaScript警报,如下所示:

if(空($ _ POST [&#39;用户名&#39;])||空($ _ POST [&#39;密码&#39;])) {echo“alert('无效组合')”; }