简体   繁体   中英

count database rows by id


I'm trying to count the $active_ids from the database. But I'm not figuring out how to do it best. As a disclaimer, I'm still learning MySQL/PHP.

this is what it echo's right now

1, 3, 4, 1, 1

and is what it will look like if it's counted

3, 1 ,1


    <?php

    $active_ids = '1, 3, 4';

        $query = "SELECT * FROM users WHERE id IN ({$active_ids})";
        $result = $mysqli->query($query);

        if($result->num_rows > 0){

                while($row = $result->fetch_assoc()){
                    echo $row['username'], "<br/>";
                }

            $query = "SELECT COUNT(*) FROM timetable WHERE dj IN ({$active_ids})";
            $result = $mysqli->query($query);
                while($row = $result->fetch_assoc()){
                    echo $row['dj'], "<br/>";
            }
        }
    ?>

I don't really know PHP, but I know SQL. It sounds like you want to use a GROUP BY clause, like this:

select dj, count(*) as n from timetable
    where dj in ({$active_ids})
    group by dj

Each row selected will have two columns. The first column (named “dj”) is the dj's user id, and the second column (named “n”) is the number of entries in timetable with that dj's id. You should be able to print the count like this:

echo $row['n'], "<br/>";

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