[英]PHP PDO fetch class returning FALSE
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. 我具有此PHP函数,该函数获取当前登录用户的数据,或者如果访客未登录或具有无效的user_id和password_hash cookie,则返回false。 For some reason,
$q->fetch()
always returns 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;
}
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. 使用确切的数据而不是查询中的占位符运行该查询不会更改任何内容,直接在我的数据库中运行该查询会返回1行,就像应该的那样。 I checked, $num does indeed equal 1. I don't know why
$q->fetch()
returns FALSE, so any pointers would be very much appreciated. 我检查了一下,$ num确实等于1。我不知道为什么
$q->fetch()
返回FALSE,所以任何指针都将不胜感激。
You're already fetching all results using fetchAll()
. 您已经在使用
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. 您只希望
$q->rowCount()
对行进行计数或将fetchAll()
返回的数组保存在某个地方,以便以后使用。
As said, you cannot use fetchAll then fetch after one query; 如前所述,您不能在一次查询后使用fetchAll然后进行fetch; but rowCount cannot be used for select.
但是rowCount不能用于选择。 A solution can be:
解决方案可以是:
You get results in an array with fetchAll: 您可以使用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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.