0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, thanks! Also, $q->rowCount() only works on DELETE, INSERT and UPDATE statements in most cases, so it isn't the most reliable option.
0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.