[英]Return MySQL Count via PHP
I have a PHP function that looks like this: 我有一个PHP函数,如下所示:
function count_creatives() {
global $db;
$q = "SELECT COUNT(DISTINCT creative) FROM actions";
return $db->query($q);
}
The $db variable contains a PDO object and is set correctly (used successfully elsewhere). $ db变量包含一个PDO对象并且设置正确(在其他地方成功使用)。
When I try to assign the result of this function to a variable, it only contains the querystring (no results). 当我尝试将此函数的结果赋给变量时,它只包含查询字符串(无结果)。
Code I'm Running: 我正在运行的代码:
$count = count_creatives();
echo $count;
Output: 输出:
PDOStatement Object ( [queryString] => SELECT COUNT(DISTINCT creative) FROM actions )
Any idea why I'm not getting the actual count (eg 2, 3, 100)? 知道为什么我没有得到实际计数(例如2,3,100)?
PDO::query() returns a PDOStatement object, or FALSE on failure. PDO :: query()返回PDOStatement对象,失败时返回FALSE。 You need to do something like, 你需要做点什么,
function count_creatives() {
global $db;
$q = "SELECT COUNT(DISTINCT creative) FROM actions";
$query = $db->query($q);
return $query->fetch(PDO::FETCH_NUM)[0];
}
You're returning the resource object from your function, not the field value. 您将从函数返回资源对象,而不是字段值。 You need to fetch the result and then return that. 您需要获取结果然后返回结果。 Please use the following: 请使用以下内容:
function count_creatives()
{
global $db;
$q = "SELECT COUNT(DISTINCT creative) AS `total` FROM actions";
$result = $db->query($q);
$actions = $result->fetchObject();
return $actions->total;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.