简体   繁体   中英

How to find no of rows with same value in php mysql

I have one table with event_id & image_id. I want to find the no of rows which with the same value -> max in this table.

means in this table output should like: 1508706279 -> image_id 4 -> no of rows

here is my table.

在此处输入图片说明

below is the code which i have tried.

$sql2 = "select image_id, COUNT(*) as count from user_likes where event_id  = '$id' GROUP BY image_id";

                    if($result2 = mysqli_query($conn, $sql2)) {

                        $result1 = mysqli_fetch_array($result2);

                        $win = $result1['image_id'];
                        $count = $result1['count'];

                    } 

Now, i can't understand what is issue but this code works fine when there are rows between id 52 to 60 it shows output:

1508706279 -> image_id 4 -> no of rows

but when i add two more rows with id 64 & 65 it shows output:

818525590 -> image_id 1 -> no of rows

help me in this what mistake i am doing here.!!

Your query return a collection of image_id and count. The collection is not ordered so you have the first one from select if you need the max try ordering by count(*) desc

  $sql2 = "select image_id, COUNT(*) as count 
            from user_likes 
            where event_id  = '$id' 
            GROUP BY image_id
            ORDER BY count(*) DESC";

and you can limit to 1 if you need one row only

  $sql2 = "select image_id, COUNT(*) as count 
            from user_likes 
            where event_id  = '$id' 
            GROUP BY image_id
            ORDER BY count(*) DESC LIMIT 1";

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