9

Use pdo fetch_group to save the number of sql as individual variables

 3 years ago
source link: https://www.codesd.com/item/use-pdo-fetch-group-to-save-the-number-of-sql-as-individual-variables.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Use pdo fetch_group to save the number of sql as individual variables

advertisements

I'm trying to do a sql COUNT with php PDO::FETCH_GROUP to avoid using three separate sql queries

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

The array for this looks like:

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

And while I can print that using a foreach within another foreach loop it's not really what I want.

I've tried also to use bindColumn with a while loop:

$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.' ';
    }

But although they both work I want to know if it's possible to save each of the counts in relevant variables?

e.g. $femaleCount, $maleCount, $unknown etc


Instead of FETCH_GROUP you need PDO::FETCH_KEY_PAIR. The link is to my article where I listed all the fetch modes explaining their purpose and possible use.

$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";
}


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK