我正在尝试为用户名、密码组合编写一个简单的验证练习,该练习将验证输入并向用户指出他们的错误所在,我得到一个奇怪的结果,我无法理解为什么。
如果用户有一个名为Password的密码,则代码将验证,但是如果他们的密码为Password1,那么即使我在数据库中更改了用户名和密码组合,我也会收到用户名和密码组合不正确的响应。
以前会有人遇到过这个问题吗?我该如何解决?
<html>
<head>
<title>Login</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<h1>Log In</h1>
<form action="login.php" method="post">
<ul id="login">
<li> Username: <br />
<input type ="text" name="username"/>
</li>
<li>
Password: <br/>
<input type="password" name="password"/>
</li>
<li>
<input type="submit" value="Log In"/>
</li>
<li>
<a href="Registration.php">Register</a>
</li>
</ul>
<?php
$username = $_POST['username'];
$password = $_POST['password'];
function user_exists($username){
$server = 'localhost';
$user='root';
$password='';
$db = 'finance_checker';
$mysqli = mysqli_connect($server, $user, $password, $db);
if(mysqli_connect_errno($mysqli)){
echo "Failed to connect to MySQL".mysqli_connect_error();
}
$res = $mysqli->query("SELECT * FROM `users` WHERE `UserName` = '$username'");
return ($res->num_rows>0);
$res->close();
}
function userLogin ($username, $password){
$server = 'localhost';
$user='root';
$pass='';
$db = 'finance_checker';
$mysqli = mysqli_connect($server, $user, $pass, $db);
$res = $mysqli->query("SELECT * FROM `users` WHERE `UserName`='$username' AND `Password` = $password");
if($res&&$res->num_rows>0){
return true;;
}else{
return false;
}
}
if(empty($_POST)==false){
if(empty($username)==true ||empty($password)==true){
echo "Please complete both sections of the form!<br />";
} else if(empty($username)==true){
echo "You must enter a username!<br />";
} else if(empty ($password)==true){
echo "You must enter a password!<br />";
} else if (user_exists($username)==false){
echo "Username cannot be found. Click on the register link to create a new account.";
} else{
$login = userLogin($username, $password);
if($login == false){
echo 'Username and Password combination is not compatible!';
} else{
header("Location:home.php ");
}
}
}
?>
</body>
</html>