Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7798825
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T00:06:37+00:00 2026-06-02T00:06:37+00:00

I have been pouring over many forums and questions similar (but not the same)

  • 0

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!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T00:06:38+00:00Added an answer on June 2, 2026 at 12:06 am

    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:

    function fieldCount($field,$condition,$table)
    {
    //This is just a file that holds the database info and can be whatever name you want
    require('database.ini');
    try{
        $dbh = new PDO("mysql:host=$db_hostname;dbname=$db_database", $db_username, $db_password);
    
        //This turns on the error mode so you get warnings returned, if any
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
        $stmt = $dbh->prepare("SELECT $field, COUNT(*) AS count FROM $table $condition GROUP BY $field");
    
    // I tried to bind my $field variable but for some reason it didn't work so I
    // commented it out below until I can look deeper into it. If anyone sees any
    // glaring errors, please point them out. It looks right to me, but as I said,
    // it's not working.
    
    //  $stmt = $dbh->prepare("SELECT :field, COUNT(*) AS count FROM $table $condition GROUP BY :field");
    //  $stmt->bindParam(':field', $field);
    
        $stmt->execute();
    
        $results=$stmt->fetchAll(PDO::FETCH_ASSOC);
        // Creates an array similar as the following:
        // $results[0][$field] $results[0]['count']
        // $results[1][$field] $results[1]['count']
        // $results[2][$field] $results[2]['count']
        // with each row as an array of values within a numeric array of all rows
    
        $dbh = null;
    }
    catch(PDOException $e)
    {
    echo $e->getMessage();
    }
    
    return $results;
    }
    

    The database.ini file might look something as simple as this:

    <?php
        //database.ini
    
        $db_hostname = 'myHostname';
        $db_database = 'databaseNameHere';
        $db_username = 'YourUserNameHere';
        $db_password = 'YourPasswordHere';
    ?>
    

    Here is how you call the function:

    <?php
    // First you have to "require" your file where the function is located,
    // whatever you name it.
    require('FieldCountFunction.php');
    
    // Determine what column in your database you want to get a count of.
    // In my case I want to count how many items there are in each individual
    // category, so the $field is Category here.
    $field = 'Category';
    
    // If there is a condition to your query, you would state it here.
    // In my case I wanted to exclude any items in my Inventory table that
    // are marked "Discontinued" in the Notes column of my database.
    $condition = "WHERE Notes NOT LIKE 'Discontinued'";
    
    $DB_Table = 'Inventory';
    
    // Now you call the function and enter the $field you want to get a count of,
    // any conditions to the query, and the database table name you are querying.
    // The results you collected in the function (it was called $results above),
    // will be dumped into a new array now called "$fieldArray" below.
    $fieldArray = fieldCount($field, $condition, $DB_Table);
    
    // To get the data out again you can do the following to cycle through the
    // numeric array of rows (that's what the "$i" is for) and from each numbered
    // row you can retrieve the "$field" and "count" that you need. Then display
    // them however you want. I'll just echo them out here.
    $i=0;
    while($i<count($fieldArray))
    {
        echo $fieldArray[$i]["$field"].' : '.$fieldArray[$i]['count'].'<br />';
        $totalCount = $totalCount + $fieldArray[$i]['count'];
        $i++;
    }
    echo $totalCount.' items total';
    ?>
    

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have been pouring over the MYSQL documentation trying to determine if my script
I have been trying to follow this old Google tutorial (could be the problem)
I have been pouring over the GWT Designer Quick Start documentation and for the
Have been reading up and checking other questions, but don't understand / can't seem
I have been poring over the PostgreSQL 9.0 documentation on Pattern Matching but I
I have been pouring over Zend_View and the various classes and interfaces that make
I've spent some time poring over the standard references, but I've not been able
Have been searching all over the internet but struggling to find my answer to
I am getting back into web development, and have been trying to go over
I have been pouring through documentation as part of my quarter long project to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.