简体   繁体   中英

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.prepared-statements.php

You can use conditional counting and sum. For this CASE statement is very good.

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. You need to use parameterized prepared statements .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM