因为 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 注入到您的数据库中。有关如何执行此操作的更多信息,请参阅此问题(堆栈溢出链接)