I just started learning mysqli last night and am currently having an issue with a function I created. The function should log in the user. However, when I type in an existing username with the authentic or a made up password, the login page reloads displaying the $user_id
. I'm at a lost at what is wrong. I didn't have this problem when I had 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;
}
And here is when I call the function login in the login page. $mysqli
is the variable containing the connection to the database.
// 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>';
}