tags:

views:

224

answers:

1

Hi everyone,

Need to count the number of rows for each category in a MySQL table using PDO. For example, I need to have the number of entries for category 1, category 2, etc. If possible, I would like to do this without having to write out an SQL statement for each category.

Thanks!

+4  A: 

The SQL you need is something like:

SELECT category_name, COUNT(*) AS total FROM category_table
GROUP BY category_name

This will return a result set that has one row for each category. Each row has two columns: the category name and the total number of records with that category name. The same technique works for category id's or any other key you may want to use.

You would use it this way:

$sql = 'SELECT category_name, COUNT(*) AS total FROM category_table '.
       'GROUP BY category_name';

$db = new PDO($database, $user, $password);
$results = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);

// $results is now an array with the query results

Edit: added sample PHP code.

Jon
+1: Just don't forget that if you add other columns, those need to be added to the GROUP BY clause as well.
R. Bemrose
Indeed. More columns need to be either added to the GROUP BY clause (which means that more than one row will be returned for each category) or processed through an aggregate function like COUNT, MAX, AVERAGE etc.
Jon
Thanks so much. I must admin that arrays have never been a strong suit of mine, for some reason. I am working with three categories - "Fire," "EMS," and "Specialty." Your above example works wonderfully as long as I use $results[0]['total'], $results[1]['total'], etc. How would I go about using $results['Fire']['total'] or something similar instead? Thanks :)
NightMICU
An update to above comment - essentially, the value returned by the count will be used to determine whether or not to show part of a page. For example, if there are no entries for the "Specialty" category, that tab will not be displayed. There may not be entries for each category at any given time, so it is essential that I be able to count the number for each category, whether or not any entries exist for that particular category. Hope this makes sense, thanks..
NightMICU
Try this: `->fetchAll(PDO::FETCH_COLUMN | PDO::FETCH_GROUP);` and do a `print_r` on the result to see how to use it.
Jon
Thanks, Jon! I may not have explained myself too well in the initial question, but the above works just fine. I ended up with: if ($results['Fire'][0] > 0) { //Do something }What I left out in the initial question is that the category column is a varchar, each entry has one of the three options based on user input from a drop-down menu.
NightMICU