I have a following problem. I have three tables: message, comment and user. I would like PHP to print the data of following fields from MySQL database as a table on my web-page: message.subject, user.username and then number of comments. Everything else works fine but I haven’t managed to get PHP to print the number of comments.
This is what I have tried to do so far:
<?php
include("info.php");
$connect;
$sql="SELECT * FROM message, user
WHERE message.userID = user.userID AND
ORDER BY message.messageID DESC";
$result=mysql_query($sql) or die(mysql_error());
$sql2="SELECT message.messageID, COUNT(*) as comments FROM comment
INNER JOIN
message ON comment.messageID = message.messageID
GROUP BY comment.messageID";
$result2=mysql_query($sql2) or die(mysql_error());
<table>
<thead>
<tr>
<th>Subject</th>
<th>Sender</th>
<th>Number of comments</th>
</tr>
</thead>
<tbody>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td>
<a href="php/message.php?id=<?php echo $rows['messageID']; ?>">
<?php echo $rows['subject']; ?>
</td>
<td>
<?php echo $rows['username']; ?>
</td>
<td>
<?php while($rows2=mysql_fetch_array($result2)){ echo $rows2['comments'];}?>
</td>
</tr>
<?php
} mysql_close(); ?>
</tbody>
</table>
Couldn’t you just get all this info with one query?
Try this script:
There are a few other corrections as well. For instance, your link doesn’t have a closing
</a>tag, and your script may be vulnerable to XSS attacks. And then there’s the nested while-loop, which was causing unnecessary complication and bugs.