Click here to Skip to main content
15,888,579 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi,

I have a users table displayed on a page with their userID and username.

I want to get a count of usernames from a seperate table (Reported Users table) and list the count alongside their respective username and userID.

In the reported table I have a userID and username, and for every time a user is reported, their username is added to the reported users table. I know how to get a count from the reported table but im unsure of how to list the amount of times their username appears in the reported users table next to their username from the users table.

PHP
$db = Database::getConnection();
				$query = 'SELECT * FROM users WHERE activated=1';
				$output = $db->query($query);
				$results = $output->fetchAll(PDO::FETCH_ASSOC);
				if (count($results) > 0) {
					echo "<table cellspacing=\"0\">";
					echo "<tr><th>UserID</th><th>Username</th><th>Reported</th></tr>";
					foreach($results as $result){
						echo "<tr>\n";
						$username = $result['username'];
						echo "<td>$result[userID]</td>";
						echo "<td>$result[username]</td>";
						$reportsQuery = "SELECT reported COUNT(*) FROM reports WHERE reported = '$username'";
						$reportsOutput = $db->query($reportsQuery);
						while ($row = $reportsOutput->fetch(PDO::FETCH_ASSOC)){
						echo '<td>Report count</td>';
						}
						echo "</tr>\n";
					}
				} else {
					echo 'There are no active users!';
				}
				echo "</table>";?>
Posted
Comments
Zoltán Zörgő 3-Feb-15 7:58am    
1) LEFT JOIN
2) subqquery

You could try something like this to get all of the details back in a single query
SQL
SELECT U.* , ISNULL(R.reportedCount,0) AS reportcount
FROM users U
LEFT OUTER JOIN (SELECT reported, COUNT(*) AS reportedCount
                    FROM reports GROUP BY reported)  R on U.username=R.reported
WHERE U.activated=1
 
Share this answer
 
v3
Option 1
SQL
SELECT username, userID, count(reports.reported) as numreports FROM 
users LEFT JOIN reports ON users.username=reports.reported
WHERE activated=1 
GROUP BY username, userID

Option 2:
SQL
SELECT username, userID, 
(select count(*) from reports WHERE users.username=reports.reported) as numreports
FROM users 
WHERE activated=1 
 
Share this answer
 
v2
Comments
CHill60 3-Feb-15 9:39am    
Caution - Option 1 will always return a minimum count of 1 as numreports because the group by causes a count of everything on the left table (users)
Zoltán Zörgő 3-Feb-15 9:41am    
True, updated

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900