-3

我创建了一个连接到数据库的登录页面。但是,为了提供消息,我使用了警报。现在,在加载页面后,我立即收到“无效用户名”警报。我希望警报仅在按下登录按钮后出现。

此外,按下登录按钮后,页面变为空白,然后出现警报,然后单击“确定”,加载 html 页面。如何在同一页面上获取警报。

文件:login.php

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <form id="Form"  method="post">
        <input id="Username" name="Username" type="text" placeholder="Username"><br>
        <input id="Password" name="Password" type="password" placeholder="Password""><br>
        <button id="Button" name="Login" type="submit">Login</button><br>
    </form>
</body>
</html>
<?php
$conn=mysqli_connect ('localhost','root','','test');
$uname=$_POST['Username'];
$passw=$_POST['Password'];
$check=mysqli_query($conn,"select Username from members where Username='$uname' and Password='$passw'");
if(mysqli_num_rows($check)==1)
{
    echo "<script>alert('Login Successful');</script>";
}
else
{
    $check=mysqli_query($conn,"select Username from members where Username='$uname'");
    if(mysqli_num_rows($check)==1)
    {
        echo "<script>alert('Invalid Password');</script>";
    }
    else
    {
        echo "<script>alert('Invalid Username');</script>";
    }
}
?>
4

3 回答 3

2

对于这样一个看似很小的事情可能会很苛刻,但这里的解决方案是使用 AJAX。假设您不了解 AJAX,我建议您在使用此解决方案后学习它。

为此,您还需要jQuery

首先,您需要将 PHP 部分包含在另一个文件中,比如说:login.php

<?php


$conn=mysqli_connect ('localhost','root','','test');
$uname=$_POST['Username'];
$passw=$_POST['Password'];
$check=mysqli_query($conn,"select Username from members where Username='$uname' and Password='$passw'");
if(mysqli_num_rows($check)==1)
{
    echo json_encode(array("msg"=>"Login Successful"));
}
else
{
    $check=mysqli_query($conn,"select Username from members where Username='$uname'");
    if(mysqli_num_rows($check)==1)
    {
        echo json_encode(array("msg"=>"Invalid Password"));
    }
    else
    {
        echo json_encode(array("msg"=>"Invalid Username"));
    }
}
?>

接下来,您将制作一个 JS 文件:

$('#form').submit(function(event) {
   $.ajax({
     method: "POST",
     url: "login.php",
     data: $("#form").serialize()
   })
   .done(function( data ) {
     alert(data['msg']);
   });
}

对不起,如果我错过了一部分,但有很多事情要做和学习让你完全理解这一点。

于 2018-10-04T13:55:25.077 回答
1

因为 PHP 是服务器端代码,所以您mysqli_num_rows($check)==1在将页面呈现给用户之前加载值,因此没有输入任何凭据。如果要对按钮单击执行操作,则需要使用客户端代码,例如 javascript。这是我为您创建的简单解决方案。

这是登录表单所在的“index.php”页面:

<html>
    <head>
        <title>Please login</title>
    </head>
    <body>
        <input id="Username" name="Username" type="text" placeholder="Username"><br>
        <input id="Password" name="Password" type="password" placeholder="Password""><br>
        <button id="Button" name="Login" onclick="checkCredentials();">Login</button><br>
        <script type="text/javascript">
            function checkCredentials(){
                var username = document.getElementById('Username').value; //Get the text from username field
                var password = document.getElementById('Password').value; //Get the text from password field

                var request = new XMLHttpRequest();

                request.onreadystatechange = function() {
                    if (this.readyState == 4 && this.status == 200) {
                        //Make your alert
                        var response = JSON.parse(this.responseText);

                        if(response.status == 200){
                            alert(response.alert);
                            /**
                            * Here, put whatever else you want to do when login is successful!
                            * My best guess is that you'd redirect the user to a page where a new
                            * PHP session is started. If you need help with this, please ask :)
                            **/
                        } else {
                            //Login has failed, display the response message
                            alert(response.alert);
                        }
                    }
                };

                //We're sending the password in plaintext over a GET request. I've done this for simplicity.
                //You should NOT send the password in plaintext on the production system. Doing this is insecure. Hash it before you send it.
                request.open("GET", "login.php?username="+ username +"password=" + password, true);
                request.send();
            }
        </script>
    </body>
</html>

现在您已经创建了登录页面,您可以创建 login.php 页面,这是一个用于检查登录详细信息的后端脚本。

<?php
    $loginStatus = array("status" => 403, "alert" => "forbidden");

    $conn=mysqli_connect ('localhost','root','','test');
    $uname=$_GET['username'];
    $passw=$_GET['password'];

    //Don't use this line in production, you should use a prepared statement instead
    $check=mysqli_query($conn,"select Username from members where Username='$uname' and Password='$passw'");

    if(mysqli_num_rows($check)==1)
    {
        $loginStatus = array("status" => 200, "alert" => "Login Successful!");
    }
    else
    {
        $check=mysqli_query($conn,"select Username from members where username='$uname'");
        if(mysqli_num_rows($check)==1)
        {
            $loginStatus = array("status" => 403, "alert" => "Invalid Password!");
        }
        else
        {
            $loginStatus = array("status" => 403, "alert" => "Invalid Username!");
        }
    }

    echo json_encode($loginStatus);
?>

代码解释:

在您的“index.php”上,有一段 javascript 向您的身份验证页面 (login.php) 发出请求(在后台)。Login.php 返回一个 JSON 数组,其中包含登录信息(如果登录成功与否),以及在 javascript alert() 中显示的消息;

什么是prepared statement

准备好的语句是使用参数而不是直接使用值的数据库查询。这更加安全,有助于防止 SQL 注入到您的数据库中。有关如何执行此操作的更多信息,请参阅此问题(堆栈溢出链接)

于 2018-10-04T13:53:14.040 回答
-4

如果提交了表单,您只希望 PHP 运行。因此,将所有 PHP 代码包装在 if 条件中。

if (!empty($_POST)) { .... rest of php code here ... }
于 2018-10-04T13:19:32.047 回答