Francois Stander
Francois Stander

Reputation: 63

Unable to get value from a PDO array

I am fairly new to PHP and have been following the Lynda.com tutorials (although they still use mysql in stead of mysqli or PDO).

I'm having problems with using the data I get from my queries.

I'll use my login page as example, leaving out the connect to db part:

$login_username = trim(htmlspecialchars($_POST['username'])); 
$password = trim(htmlspecialchars($_POST['password'])); // from login form

$stmt = $db->prepare("SELECT * FROM users 
                     WHERE username = :login_username");

$stmt->bindParam(':login_username', $login_username);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0 && $result = password_verify($password,$result['hashed_password'])) {
$_SESSION['logged_in_id'] = $result['id'];
$_SESSION['logged_in_username'] = $login_username; //this was the only way I could pass the username as I could not get it from $result['username']
$_SESSION['first_name'] = $result['first_name'];
$_SESSION['last_name'] = $result['last_name'];

Nothing gets passed to the session and there are no errors. I also can't echo out the value of $result. If I just try to echo $result, then I just get the value 1

Please help!

Upvotes: 0

Views: 42

Answers (1)

jeroen
jeroen

Reputation: 91734

Your problem is:

... && $result = password_verify($password,$result['hashed_password'])

Note that $result is an array that contains the row that you just fetched and you are assigning it a new value here; you are overwriting your $result variable so all assignments afterwards will fail.

You probably want something like:

... && password_verify($password,$result['hashed_password'])

Also note that you should not rely on the rowCount() as that is not necessarily what you expect for a SELECT statement.

As you are fetching a row already, you can simply do:

 if ($result && password_verify($password,$result['hashed_password']))

If there is no result, the second condition will never be checked so it will not lead to warnings or errors.

Upvotes: 1

Related Questions