PHP警报出现在加载页面上并使页面空白

时间:2018-10-04 13:16:14

标签: php html

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

此外,在按下“登录”按钮后,页面将变为空白,然后出现警报,然后单击“确定”,将加载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>";
    }
}
?>

3 个答案:

答案 0 :(得分: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']);
   });
}

对不起,如果我错过了一部分,但是还有很多事情要做,可以学到一些,以便您完全理解。

答案 1 :(得分: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注入数据库。 See this question for more info how to do it (stack overflow link)

答案 2 :(得分:-4)

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

if (!empty($_POST)) { .... rest of php code here ... }