Reputation: 334
I have this PHP function that gets the data of the currently logged in user, or returns false if the visitor either isn't logged in, or has invalid user_id and password_hash cookies. For some reason, $q->fetch()
always returns FALSE.
if( $_COOKIE['cuid']!='' && $_COOKIE['cuph']!='' )
{
try
{
$q = $db->prepare( 'SELECT * FROM users WHERE user_id = ? AND password = ?' );
$data = array( $_COOKIE['cuid'], $_COOKIE['cuph'] ); // id and password hash
$q->execute($data);
$num = count( $q->fetchAll() ); // in my case, $num is set to 1
if( $num == 1 )
{
$q->setFetchMode(PDO::FETCH_CLASS, 'User');
$user = $q->fetch(); // $user is set to FALSE for some reason
return $user;
} else {
return FALSE;
}
}
catch( Exception $e )
{
$db->rollBack();
echo 'Error: ' . $e->getMessage();
}
} else {
return FALSE;
}
Running that with exact data instead of placeholders in the query doesn't change anything, and running that query directly in my database returns 1 row, like it should. I checked, $num does indeed equal 1. I don't know why $q->fetch()
returns FALSE, so any pointers would be very much appreciated.
Upvotes: 0
Views: 1391
Reputation: 1
As said, you cannot use fetchAll then fetch after one query; but rowCount cannot be used for select. A solution can be:
You get results in an array with fetchAll:
$results=$q->fetchAll()
Then you can get and use or check the number, for example:
echo count( $results);
And get and work with results, for example:
foreach ($results as $result)
{
var_dump($result);
}
Upvotes: 0
Reputation: 522032
You're already fetching all results using fetchAll()
. The result set is thereby exhausted, you cannot fetch any more results from it. You simply want $q->rowCount()
to count the rows or save the array returned by fetchAll()
somewhere and use it later.
Upvotes: 1