PHP/MySQL News with Comments - Displaying the comments
(Page 4 of 7 )
The next thing we want to do is display comments. Like I mentioned earlier, we need to query the comments table for rows that where news_id matches the piece of news being viewed.
<?php function displayComments($id) { /* bring db connection variable into scope */ global $db; /* query for comments */ $query = "SELECT * FROM news_comments WHERE news_id=$id"; $result = mysql_query ($query); echo "Comments:<BR><HR width=\"300\">\n"; /* display the all the comments */ while ($row = mysql_fetch_assoc ($result)) { echo "<TABLE border=\"1\" width=\"300\">\n"; $name = htmlentities ($row['name']); echo "<TR><TD><b>by: $name</b></TD></TR>\n"; $comment = strip_tags ($row['comment'], '<a><b><i><u>'); $comment = nl2br ($comment); echo "<TR><TD>$comment</TD></TR>\n"; echo "</TABLE>\n"; echo "<BR>\n"; } /* add a form where users can enter new comments */ echo "<HR width=\"300\">"; echo "<FORM action=\"{$_SERVER['PHP_SELF']}" . "?action=addcomment&id=$id\" method=POST>\n"; echo "Name: <input type=\"text\" " . "width=\"30\" name=\"name\"><BR>\n"; echo "<TEXTAREA cols=\"40\" rows=\"5\" " . "name=\"comment\"></TEXTAREA><BR>\n"; echo "<input type=\"submit\" name=\"submit\" " . "value=\"Add Comment\"\n"; echo "</FORM>\n"; } ?> |
As you can see, this is very similar to the displayNews function. In both, all we are doing is querying the database and looping to display all the data returned. On way you could enhance this would be to add a postdate field to the comments table and then order the comments query by date.
Next: Displaying one item with comments >>
More Database Articles Articles
More By Matt Wade