Click here to Skip to main content
15,891,423 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

below I have some code that displays the 3 latest threads on a discussion board. Along with an image, the thread name, and the last activity, I want to display a count of the replies associated to that thread.

I have a database table for threads and a database table for replies, and the replies are linked to the threads table (threadID) on a column called replyThreadID (FK to threads.threadID.

PHP
$db = Database::getConnection();
			$query = 'SELECT * FROM threads AS t 
			JOIN profile AS p ON t.threadBy = p.username 
			WHERE t.threadTopic="'.$topic.'" 
			ORDER BY lastActive DESC LIMIT 3';
			$output = $db->query($query);
			$results = $output->fetchAll(PDO::FETCH_ASSOC);
				if (count($results) > 0) {
					echo "<table>\n";
					echo "<tr><th colspan=2>".$topic."</th>
					<th>Replies</th>
					<th>Last activity</th></tr>\n";
					foreach($results as $result){
						$threadID = $result['threadID'];
						//get count of replies for each thread
						$replies = (count());
						$src = $result['image'];
						$image = '<img src="'.$src.'"></img>';
						echo "<tr>\n";
						echo "<td>$image</td>";
						echo "<td>$result[threadName]</td>";
						echo "<td>$replies</td>";
						echo "<td>$result[lastActive]<br>By: $result[threadBy]</td>";
						}
						echo "</tr>\n";
						echo "</table>";
					}
			}


Is it possible to get a count for the amount of replies where the replyThreadID = threadID? Should it be inside or outside the foreach?
Posted
Comments
Sascha Lefèvre 9-Apr-15 10:57am    
Did you check out my proposed solution yet?

1 solution

You can query the amount of replies in your first query (I named the result column "ReplyCount" here):
PHP
$query = 'SELECT *,
          (SELECT Count(replyThreadID) FROM replies WHERE replyThreadID = t.threadID) AS ReplyCount
          FROM threads AS t 
          JOIN profile AS p ON t.threadBy = p.username 
          WHERE t.threadTopic="'.$topic.'" 
          ORDER BY lastActive DESC LIMIT 3';

And then simply read that column as any other.

SQL-Fiddle: http://sqlfiddle.com/#!9/6bd0f/2[^]

By the way, I would suggest you explicitly specify the columns you want to select, instead of using SELECT *
 
Share this answer
 
Comments
jba1991 9-Apr-15 11:37am    
Hi. Thats exactly what I need. I looked at your SQL fiddle and thats what I want to work. How to I call replyCount and store it into a variable?
Sascha Lefèvre 9-Apr-15 11:42am    
It's a column in your query-result like any of the other, "regular" columns. So you can read it in your foreach-loop like so:
$replyCount = $result['ReplyCount'];
jba1991 9-Apr-15 16:18pm    
Thanks! that works.

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