[英]Group and count PDO output
I have a query:我有一个查询:
$myData = $db->query("
SELECT *
FROM t1
WHERE event = '$eid'
", PDO::FETCH_OBJ);
that returns results in an a form of an array:以数组形式返回结果:
Array (
[0] => stdClass Object
(
[id] => 1
[even] => 1
[response] => NO
[adult] =>
[child] =>
)
[1] => stdClass Object
(
[id] => 2
[event] => 1
[response] => YES
[adult] => 1
[child] => 3
)
)
I need to get the following counts:我需要得到以下计数:
Total for each response: YES and NO If YES: Total Adults Total Children每个回答的总数:是和否 如果是:成人总数 儿童总数
Can I get it from a query or do I need to manipulate the array to get the counts?我可以从查询中获取它还是需要操纵数组来获取计数?
You could iterate over the result array from your current query or you could get the counts from another query.您可以从当前查询中迭代结果数组,也可以从另一个查询中获取计数。
-- display count of YES responses and total adults and children
SELECT COUNT(*), SUM(adult), SUM(child)
FROM t1
WHERE event = '$eid'
AND response = 'YES';
-- display count of NO responses
SELECT COUNT(*)
FROM t1
WHERE event = '$eid'
AND response = 'NO';
Probably best to use them in prepared statements.可能最好在准备好的语句中使用它们。
https://www.php.net/manual/en/pdo.prepare.php https://www.php.net/manual/en/pdo.prepare.php
https://www.php.net/manual/en/pdo.prepared-statements.php https://www.php.net/manual/en/pdo.prepared-statements.php
You can use conditional counting and sum.您可以使用条件计数和求和。 For this
CASE
statement is very good.对于这个
CASE
陈述是非常好的。
SELECT
COUNT(CASE response WHEN 'YES' THEN 1 ELSE NULL END) as YesResponses,
COUNT(CASE response WHEN 'NO' THEN 1 ELSE NULL END) as NoResponses,
SUM(CASE response WHEN 'YES' THEN adult ELSE 0 END) as Adults,
SUM(CASE response WHEN 'YES' THEN child ELSE 0 END) as Children
FROM t1
However, please note your code is vulnerable to SQL injection.但是,请注意您的代码容易受到 SQL 注入的影响。 You need to use parameterized prepared statements .
您需要使用参数化准备好的语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.