我昨晚刚开始学习 mysqli,目前我创建的函数有问题。该功能应登录用户。但是,当我使用真实密码或编造密码输入现有用户名时,登录页面会重新加载并显示$user_id
. 我对出了什么问题感到迷茫。我有mysql的时候没有这个问题。
/**
* Returns FALSE, if no valid user found
* Returns user_id of matching user with $username and $password
*/
function login ($mysqli, $username, $password) {
// not required at all
// $user_id = user_id_from_username($mysqli, $username);
// initialize, in case we do not get a mysqli-statement
$userID = FALSE;
$password = md5($password);
$stmt = $mysqli->prepare(
"SELECT `user_id` "
. " FROM `users` "
. " WHERE ( `username` = ? ) "
. " AND ( `password` = ? ) "
);
if ( $stmt ) {
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($userID);
if ( TRUE !== $stmt->fetch()) {
$userID = FALSE;
}
}
$stmt->close();
return $userID;
}
这是我在登录页面中调用函数登录的时候。$mysqli
是包含与数据库的连接的变量。
// Now, needs to check against FALSE to work [changed by @SteAp]
// var_dump( $login ); returns with int(1)
// and this is what I want, the integer 1
//Sends me to start.php but start.php does not recognize
//the variable $_SESSION['user_id']
if ( FALSE === ($login = login($mysqli, $username, $password)) ) {
$errors[] = 'That username/password combination is incorrect';
} else {
$_SESSION['user_id'] = $login;
header('Location: start.php');
exit();
}
if (empty($errors) === false) {
echo '<div>'. output_errors($errors) . '</div>';
}