0

我有这个 PHP 函数,它获取当前登录用户的数据,或者如果访问者没有登录,或者有无效的 user_id 和 password_hash cookie,则返回 false。出于某种原因,$q->fetch()总是返回 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;
}

在查询中使用精确数据而不是占位符运行它不会改变任何内容,并且直接在我的数据库中运行该查询会返回 1 行,就像它应该的那样。我检查了一下,$num 确实等于 1。我不知道为什么$q->fetch()返回 FALSE,所以非常感谢任何指针。

4

2 回答 2

1

您已经使用fetchAll(). 结果集因此用尽,您无法从中获取更多结果。您只是想$q->rowCount()计算行数fetchAll()保存某处返回的数组并稍后使用它。

于 2012-10-15T12:52:52.613 回答
0

如前所述,您不能在一个查询后使用 fetchAll 然后 fetch;但 rowCount 不能用于选择。解决方案可以是:

您可以使用 fetchAll 在数组中获得结果:

$results=$q->fetchAll()

然后就可以获取并使用或查看号码,例如:

echo count( $results);

并获取并处理结果,例如:

foreach ($results as $result)
{
   var_dump($result);
}
于 2014-09-26T20:44:36.440 回答