密码正确但密码同时不正确

时间:2012-12-21 00:46:53

标签: php mysql

因此,每当我登录并且密码正确时,它就会说出来 密码不正确。我该如何解决这个

<?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");
}
?>

1 个答案:

答案 0 :(得分: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 :: __构建体()

如下面的评论中所述 - 您应该使用PDO和准备好的查询