使用pdo fetch_group将sql计数保存为单个变量

时间:2017-01-19 01:08:56

标签: php mysql pdo count

我尝试使用php PDO :: FETCH_GROUP进行sql COUNT以避免使用三个单独的sql查询

$genders = $db->query('SELECT COUNT(memberID), gender FROM members WHERE gender IS NOT NULL GROUP BY gender')->fetchAll(PDO::FETCH_GROUP);

这个数组看起来像是:

Array ( [3] => Array ( [0] => Array ( [gender] => Female [0] => Female ) [1] => Array ( [gender] => Male [0] => Male ) ) [2] => Array ( [0] => Array ( [gender] => Unknown [0] => Unknown ) ) )

虽然我可以在另一个foreach循环中使用foreach打印它,但它并不是我想要的。

我还尝试将bindColumn与while循环一起使用:

$stmt = $db->prepare('SELECT m.gender, COUNT(*) as count FROM members m WHERE m.gender IS NOT NULL GROUP BY m.gender');
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_BOUND);
$stmt->bindColumn('count', $count);
$stmt->bindColumn('gender', $gender);
while ($row = $stmt->fetch())
    {
        echo $gender.' - '.$count.' ';
    }

但是虽然它们都有效但我想知道是否可以将相关变量中的每个计数保存起来?

e.g。 $ femaleCount,$ maleCount,$ unknown等

2 个答案:

答案 0 :(得分:2)

您需要PDO::FETCH_KEY_PAIR而不是FETCH_GROUP。链接到我的文章,其中列出了解释其目的和可能用途的所有获取模式。

$sql = 'SELECT gender, COUNT(*) FROM members WHERE gender IS NOT NULL GROUP BY gender';
$data = $db->query($sql)->fetchAll(PDO::FETCH_KEY_PAIR);
foreach ($data as $gender => $count)
{
    echo "$gender - $count\n";
}

答案 1 :(得分:1)

我将使用您的第二个查询并稍微更改一下。总的来说,您的查询没问题,但您必须使用Associative array将数据存储在其中,然后在代码中使用它。

查询将如下:

$strSQL = 'SELECT gender, COUNT(*) as member_count FROM members WHERE gender IS NOT NULL GROUP BY gender';

由于您没有向查询传递任何变量,因此用户prepare无需使用简单的query

所以代码将是这样的:

$arrMembers = array();

$strSQL = 'SELECT gender, COUNT(*) as member_count FROM members WHERE gender IS NOT NULL GROUP BY gender';
$result = $db->query($strSQL);
while($row = $result->fetch(PDO::FETCH_ASSOC))
    $arrMembers[$row['gender']] = $row['member_count'];

现在您有一个名为$arrMembers的数组,其中包含所有返回的记录。数组每一行的关键是"性别"并且该行的值为"成员计数"

在此之后,您可以使用此代码来回显代码中任何性别的成员数量:

echo $arrMembers['Female']; // Will print number of female members
echo $arrMembers['Male']; // Will print number of male members
echo $arrMembers['Unknown']; // Will print number of members with unknown gender