doudao2954 2010-05-12 20:23
浏览 69
已采纳

使用PDO计算MySQL表中的行数

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!

  • 写回答

1条回答 默认 最新

  • dongmeng4742 2010-05-12 20:25
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退