I have been pouring over many forums and questions similar (but not the same) as what I am trying to accomplish. I am updating my old mysql queries to PDO. I have seen many accounts of people having trouble using COUNT(*) in PDO and several posts explaining using query() instead of fetch(), or using rowCount() and sometimes fetchColumn().
However they seem to be for checking whether a query returns any, or zero, rows in the query. Maybe to test if a query is valid or to return a single line listing how many rows that single query returns? That’s not what I am trying to do (or I’m looking at it wrong).
What I want to accomplish is to get a list of how many times each unique item occurs in a given column. I have a paintball website where I want to list how many items I have for each category. The old mysql code (snipped for brevity) goes something like this:
$query = "SELECT Category, COUNT(*) FROM table WHERE Notes NOT LIKE 'Discontinued' GROUP BY Category";
$result = mysql_query($query);
$num_results = $result->num_rows;
while($row=mysql_fetch_array($result, MYSQL_NUM)) {
echo "$row[0]: $row[1]<br />";
}
My results would be:
Air: 312
Markers: 627
Masks: 124
Paint: 97
etc, etc.
So now I’m trying to accomplish the same results with PDO and have tried about a dozen different suggestions I’ve pulled from the questions others have asked. I usually like to hack these problems out myself and this is the first time I’ve had to throw in the towel and actually post my own problem on a PHP forum. I’ve gotten myself so confused I don’t know which way is up anymore.
Any guidance from a fresh perspective would be GREATLY appreciated. There must be a way that I’m not seeing or misunderstanding. THANKS in advance!
For anyone who may be struggling with this concept, here is what I came up with so far. I’m sure there are cleaner methods of doing this, but it seems to work fine for now. Since I am also trying to incorporate more object oriented coding into my bag of tricks, I ended up putting the business end of the solution into a function. If I accumulate a couple more as I rebuild my site I will probably end up grouping them together into a PDO wrapper class for myself, or something of that nature.
Here is my function:
The database.ini file might look something as simple as this:
Here is how you call the function:
This will give results similar to the following:
Accessories : 638
Markers : 432
Masks : 146
Packs : 93
Paint : 47
1356 items total
I hope this helps someone out there. And if anyone can shed some light as to why my binding didn’t work, I’d appreciate it. If not, I’m sure I’ll figure it out eventually.