PHP PDO Help Required
I am trying to fetch the UserID of the user that has just logged in and store it in $_SESSION['UserID'], however it is not doing so.
开发者_StackOverflow社区Doesn't store it. Array ( [LoggedIn] => 1 [UserID] => )
// Database Connection File
require("../system/config.php");
$user['username'] = $_POST['username'];
$user['password'] = md5($_POST['password']);
$login_check = $DBH->prepare("SELECT Username, Password FROM Users WHERE Username = ? AND Password = ?");
$login_check->execute(array($user['username'], $user['password']));
if(count($login_check) == 1) {
session_start();
$row = $login_check->fetch();
$_SESSION['LoggedIn'] = 1;
$_SESSION['UserID'] = $row['UserID'];
print_r($_SESSION);
}
else {
echo "You have entered an incorrect Username and Password, please try again.";
}
Edit: The answer you are probably looking for is that you aren't selecting UserID
in your query. But you should still look at what I wrote below.
You'd should use if ($login_check->rowCount() == 1)
instead of count()
Alternatively, it would be better to fetch()
the password for the username and check it in php to see if it's correct because then you can detect and store bad password attempts for each user and possibly deny access for a while if there have been too many.
$login_check = $DBH->prepare("SELECT UserID, Password FROM Users WHERE Username = ?");
$login_check->execute(array($user['username']));
$row = $login_check->fetch();
if (!empty($row)) {
// user exists
if ($row['Password'] == $user['password']) {
// login success
}
else {
// bad password attempt
}
}
else {
// non-existant user
}
精彩评论