从数据库中获取数据

时间:2013-02-28 17:55:27

标签: php sql

我正在尝试为学校项目开发一个登录系统,但我遇到了这个bug,我不知道如何修复它。

在我的数据库中,我将密码spy123存储在sha256哈希中,但是当我尝试在php中获取它时,我得不到任何回报。

当前代码:

// checks if the user/password combination works.
// $username | String - the username of the user to login
// $password | 32byteHash - the hashed password of the user
// return | Boolean - Returns true if the password works for that user.
function forumLib_checkLogin($username, $password){
    $goodLogin = false; //Assume the password is wrong.

    $obtainUserPassword_query = "SELECT password FROM forum_users WHERE username = '$username'";

    $dbc = forumLib_connectToDB();
    $results = mysqli_query($dbc, $obtainUserPassword_query);
    forumLib_closeConnectionToDB($dbc);

    echo "query: $obtainUserPassword_query <br />";
    echo "results: ".mysqli_fetch_array($results)."<br />";
    $row = mysqli_fetch_array($results);
    echo "row[0]: ".$row[0]."<br />";
    echo "password: $password <br />";
    echo "DBpassword: $passwordOnDB <br />";

    //if user exists
    if($results != false){
        //get password from DB
        $row = mysqli_fetch_array($results);
        $passwordOnDB = $row['password'];

        //check password
        if($password == $passwordOnDB){
            //successfull login
            $goodLogin = false;
        }
    }

    return $goodLogin;
}

输出:

change password request detected 
query: SELECT password FROM forum_users WHERE username = 'SpyMaster356' 
results: Array
row[0]: 
password: 7d9519224964c72a90b342c565fab1e4582d0e974043798f940b471304db0e24 
DBpassword:
Current password does not match records.

sql查询没有错,因为当我手动输入时,我得到7d9519224964c72a90b342c565fab1e4582d0e974043798f940b471304db0e24

这让我很困惑。

2 个答案:

答案 0 :(得分:4)

第一次调用mysqli_fetch_array后,您已经消耗了第一行数据。随后当您尝试将其捕获到$row变量中时,该行已被使用而未保存:

// Prints  'Array'. Did not save the result
echo "results: ".mysqli_fetch_array($results)."<br />";

// Doesn't get anything because the row has been previously fetched
$row = mysqli_fetch_array($results);

答案 1 :(得分:0)

更改以下细分

echo "query: $obtainUserPassword_query <br />";
echo "results: ".mysqli_fetch_array($results)."<br />";
$row = mysqli_fetch_array($results);
echo "row[0]: ".$row[0]."<br />";
echo "password: $password <br />";
echo "DBpassword: $passwordOnDB <br />";

首先填充$row数组,然后将其用于echo

echo "query: $obtainUserPassword_query <br />";
$row = mysqli_fetch_array($results);
echo "results: ". print_r($row) ."<br />";
echo "row[0]: ".$row[0]."<br />";
echo "password: $password <br />";
echo "DBpassword: {$row[0]} <br />";