出于某种原因,当我在表单中输入现有的用户名和密码时,输出总是'用户不存在',我怎么能改变它以便如果用户存在则将用户带到welcome.php页面如果用户没有,则“用户不存在”。该数据库名为TEST,该表名为USERS。
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user = $conn->real_escape_string($_POST['username']);
$pass = $conn->real_escape_string($_POST['password']);
$query = "SELECT `username` AND `password` FROM `users` WHERE `username` = '$user' AND `password` = '$pass'";
$result = $conn->query($query);
if($result->num_rows < 0) {
header('Location:welcome.php');
die();
}
else $message = 'User does not exist';
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
</head>
<body>
<form method="post" action="testing.php" enctype="multipart/form-data">
<?php if(isset($message)) : ?>
<div class="error"><?php echo $message; ?></div>
<?php endif; ?>
Username: <input type="text" value="" name="username" /><br /><br />
Password: <input type="text" value="" name="password" /><br /><br />
<input type="submit" name="submit" value="Log In"/><br /><br />
<a href="register.php">Register</a>
</form>
</body>
</html>
答案 0 :(得分:2)
num_rows()
永远不会返回小于零。它会在失败时返回布尔值false,或0或正整数。如果用户不存在或提供了错误的密码,则将返回零行:
if ($result->num_rows == 0) {
die("Wrong user/pass");
} else if ($result->num_rows > 1) {
die("Duplicate user accounts!");
} else {
die("Welcome");
}