douye5949 2017-11-12 17:05
浏览 120
已采纳

基于PHP Mysql列对结果进行分组和计数

I have a table recording hits to pages like this :

id  |  ip_address       | page_id
---------------------------------------
1   |  192.123.456.78   | 2787321    
2   |  192.000.000.00   | 2787321
3   |  192.123.456.78   | 342415
4   |  192.123.456.78   | 2787321
5   |  192.432.999.80   | 2787321

I'm getting the results like this :

$getHits = $wpdb->get_results( "SELECT * FROM $table WHERE page_id = $pageID" );

I want to display the results grouped by ip_address based on how many times each IP accessed the same page_id.

Example of desired output (where $pageID = 2787321) :

192.123.456.78 - 2 Views
192.000.000.00 - 1 View
192.432.999.80 - 1 View

I've been trying a few things (grouping mainly and running through while and foreach loops) but it quickly got really complicated and I can't get it to work.

Could somebody point me in the right direction please?

  • 写回答

1条回答 默认 最新

  • dseigqk7443 2017-11-12 17:20
    关注

    You should not use var for dinamic query you are at risk of sqlinjection anyway

     $wpdb->get_results( "SELECT ip_address, count(*) hits  
              FROM $table WHERE page_id = $pageID 
              GROUP BY ip_address 
              ORDER BY hits DESC" );
    

    http://www.mysqltutorial.org/mysql-group-by.aspx

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

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件