简体   繁体   中英

Showing number of rows created by each user

I need to show the number of entries created by each user in a table named "RE". Only the non empty entries have to be counted, by a column named "DD". The result have to be shown in a table. I already tried to do it like that, but to no avail:

<?php
if ($username = 'John Doe') {
    echo "<table>";
    $query = "SELECT user, COUNT(DISTINCT DD) AS number FROM RE GROUP BY user";

    $results = mysqli_query($conn, $query);

    for ($i = 0; $i < count($results); $i++) {

        foreach ($user[$i] as $field => $value) {

            if ($field == "number") {$number = $value;}
        }
        echo "<tr><td>".$user."</td><td>".$number."</td></tr>";
    }
    echo "</table>";
}

?>

What am I missing?

Off the top of my head, counting distinct may not be what you want, and also you could have empty string, in addition to NULL for your "empty entries." If so, then it might be appropriate to count entries which are non NULL and non empty string.

SELECT
    user,
    SUM(CASE WHEN COALESCE(DD, '') <> '' THEN 1 ELSE 0 END) AS number
FROM RE
GROUP BY user

The correct way to count "non-empty" results is something like this:

SELECT user, COUNT(DD) AS number
FROM RE
GROUP BY user;

This assumes that "empty" is NULL .

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