In this code fetch(PDO::FETCH_ASSOC) retunrs false even if $row>0.
I couldn’t find why this is happening.
Here session is not set as $member is null.
<?php
$sql = "SELECT * FROM members WHERE username=:decrypted_login and password=:decrypted_pass";
$result = $dbh->prepare($sql);
$result->bindParam(':decrypted_login', $decrypted_login);
$result->bindParam(':decrypted_pass', $decrypted_pass);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
if($rows > 0)
{
$member = $result->fetch(PDO::FETCH_ASSOC);
session_regenerate_id();
$_SESSION['SESS_MEMBER_ID'] = $member['member_id'];
$_SESSION['SESS_PASSWORD'] = $member['password'];
$_SESSION['SESS_FIRST_NAME'] = $member['firstname'];
session_write_close();
}
?>
I’ve read many and stackoverflow questions and forums but couldn’t find a solution for this.
var_dump($row); // gives an array
var_dump($member) //shows bool(false).
Advertisement
Answer
You are using fetch
instead of rowCount
:
$rows = $result->rowCount();
From PDO::fetch()
:
Fetches the next row from a result set.
The return value of this function on success depends on the fetch type. In all cases,
FALSE
is returned on failure.
I’d assume here that only 1 user can exist in the database with those credentials, when you first execute the $rows = $result->fetch(PDO::FETCH_NUM);
, the resultset cursor is moved over to the next row-set (which doesn’t exist, as there was only a single row).
Therefore, you get a false
in the later call.