PHP登录脚本-密码不正确,但用户存在


PHP Login Script - The password is incorrect but the user exists?

我的用户名&密码是正确的,但当我运行这个脚本,当我测试我的登录时,我一直得到="密码不正确,但用户存在"。有人能帮忙吗?

这是我的脚本;

<?php
include ("db.php");
if (isset($_SESSION['loggedin']) == "1") {
    echo "You are already logged in. <a href='"index.php'">Go home</a>";
} else {
    if (isset($_POST['login'])) {
        $username = strip_tags(mysql_real_escape_string($_POST['username']));
        $password = md5(strip_tags(mysql_real_escape_string($_POST['password'])));
        if (empty($username) || empty($password)) {
            echo "Enter both fields.";
        } else {
            $userQ = mysql_query("SELECT * FROM users WHERE `username` = '{$username}'");
            if (mysql_num_rows($userQ) == 0) {
                echo "This user does not exist.";
            } else {
                $userA = mysql_fetch_array($userQ);
                if ($password !== $userA["password"]) {
                    echo "The password is incorrect but the user exists.";
                } else {
                    $_SESSION['loggedin'] = "1";
                    header("Location: index.php");
                    exit;
                }
            }
        }
    }
?>
<form method="post">
    Username: <input type="text" name="username" maxlength="25" /><br />
    Password: <input type="password" name="password" maxlength="20" /><br />
    <input type="submit" name="login" value="Login" />
</form>
 <?php
}
?>

任何帮助将是伟大的,我刚刚开始学习php,不确定如果这段代码是正确的。

$userA = mysql_fetch_array( $userQ );这将返回数组。您需要迭代它并返回关联数组以检查每条记录,如;

.....
while ($row = mysql_fetch_assoc( $userQ)) {
    $userA = $row["password"];
}
if ( $password !== $userA["password"] ) {
    echo "The password is incorrect but the user exists.";
}
.....

上面的代码有迭代,但它总是有一个结果,因为用户名是唯一的(我认为)

我认为您可能有多个用户具有相同的用户名。请检查您的数据库。如果没有,那么在对其使用md5之前尝试删除mysql_real_escape_string()

如果你开始学习PHP,那么就不要再使用mysql函数了。尝试使用mysql或PDO扩展。