简体   繁体   中英

Counting number of rows in MySQL table using PDO

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!

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.

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