-6

因此,每当我登录并且密码正确时,它都会说密码不正确。我将如何解决这个问题

<?php
session_start();
require "php/dbc.php";

$username     = mysql_real_escape_string($_POST['username']);
$password     = mysql_real_escape_string($_POST['password']);
$enc_password = md5($password);

if ($username && $password) {
    $query  = mysql_query("SELECT * FROM login WHERE username='$username'");
    $numrow = mysql_num_rows($query);
    if ($numrow != 0) {
        while ($row = mysql_fetch_assoc($query)) {
            $db_username  = $row['username'];
            $enc_password = $row['password'];
        }
        if ($username == $db_username && $enc_password == $db_password) {
            //echo "Logged in <a href='members.php'>Click here to enter the members area</a>";
            $_SESSION['username'] = $db_username;
            header("location: members.php");
        } else {
            header("location: top_nav.html?error=Incorrect Password");
        }
    } else {
        header("location: top_nav.html?error=That user doesn't exist");
    }
} else {
    header("location: top_nav.html?error=All fields are required");
}
?>
4

1 回答 1

2

您的错误在于如何获取和测试数据库存储的密码:

while ($row = mysql_fetch_assoc($query)){
    $db_username = $row['username'];
    $enc_password = $row['password']; // this should probably be $db_password
}
if ($username == $db_username && $enc_password == $db_password){ 
// this condition will be false as $db_password is null, 
// and so not equal to $enc_password which is currently set to the database value

您的方法有点迂回 - 通常,我会查询用户名和加密的传入密码,而不是从数据库中加载密码以供稍后测试。

另外 - 你真的应该注意 mysql 库的 PHP 手册页上的大红框:

此扩展自 PHP 5.5.0 起已弃用,并将在未来删除。相反,应该使用 MySQLi 或 PDO_MySQL 扩展。另请参阅 MySQL:选择 API 指南和相关的常见问题解答以获取更多信息。此功能的替代方案包括:

mysqli_connect()

PDO::__construct()

正如下面的评论中提到的 - 你应该使用 PDO 和准备好的查询

于 2012-12-21T00:59:22.060 回答