Reputation: 701
Problem: so whenever i try to login it returns the following error: Notice: Trying to get property 'user_id' of non-object in /butler/Classes/users/users.php on line 191
This happens cause the fetch method where I try to retrieve the user_id from the table comes empty, although the fetchColumn()
functions shows that 1 row is found in the query.
I already checked the database table and the naming is correct. Also the html form is passing the parameters correctly that why I didn't posted that part of the code.
login page php
if (!empty($_POST['btnLogin'])) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if ($username == "") {
$login_error_message = 'Username field is required!';
} else if ($password == "") {
$login_error_message = 'Password field is required!';
} else {
$user_id = $app->Login($username, $password); // check user login
if($user_id > 0)
{
$_SESSION['user_id'] = $user_id; // Set Session
header("Location: dashboard/layout.php"); // Redirect user to the profile.php
}
else
{
$login_error_message = 'Invalid login details!';
}
}
}
function login
public function Login($username, $pass)
{
try {
$db = DB();
$query = $db->prepare("SELECT user_id FROM start_users WHERE (user_start= :username) AND (psw= :pass) ");
$query->bindParam("username", $username, PDO::PARAM_STR);
//$enc_password = hash('sha256', $password);
$query->bindParam("pass", $pass, PDO::PARAM_STR);
$query->execute();
if ($query->fetchColumn() > 0) {
$result = $query->fetch(PDO::FETCH_OBJ);
echo 'resultado'.$result.' ';
print_r($query->errorInfo());
return $result->user_id;
} else {
return false;
}
} catch (PDOException $e) {
exit($e->getMessage());
}
}
Upvotes: 0
Views: 76
Reputation: 57121
Your call to
if ($query->fetchColumn() > 0) {
is retrieving the row and so the next call to
$result = $query->fetch(PDO::FETCH_OBJ);
is trying to read the another row, which I assume doesn't exist.
You should instead just make the one call
if ($result = $query->fetch(PDO::FETCH_OBJ)) {
I would also suggest the you look into How to use password_hash as your current method is using plain passwords which aren't recommended.
Upvotes: 2