I am having a problem with an "if/else" statement.
I have two tables, an articles table for news articles and a comments table for comments on news articles from the articles table. The tables share a common field "aid".
If there are comments in the comments table that corresponds to the ID of an article in the articles table then I would want all comments to be displayed. Else I would want a "No Comments" message to be displayed. Below is the code of how I set this up.
//First grab the associated article id from the index page link and display the full article on this page
$id = $_GET['aid'];
//build the sql to grab the data in the articles table in mysql
$sqlCommand = mysql_query("SELECT * FROM articles WHERE aid='$id'");
//loop through the data in the articles table
while($row = mysql_fetch_array($sqlCommand)){
$id = $row['aid'];
$catid = $row['catid'];
$title = $row['title'];
$pic = $row['picURL'];
$picAlt = $row['picALT'];
$picTitle = $row['picTitle'];
$content = $row['article_body'];
$date = $row['reported_date'];
$formID = 'cicadas_details.php?aid='.$id;//echo this variable created so that users can post comments to a particular article since the form is below
}
//build the sql to grab the data in the comments table if a comment exists for this article id in mysql
$sqlComments = mysql_query("SELECT * FROM comments WHERE aid='$id' ORDER BY cid") or die(mysql_error());
$total_rows = mysql_num_rows($sqlComments); //Grab the total number of comments based on this article id
//loop through the data in the comments table and grab all the comments with the same id.
$displayComments = "";
while($row = mysql_fetch_array($sqlComments)){
$caid = $row['aid'];
$name = $row['name'];
$email = $row['email'];
$cmtDate = $row['comments_date'];
$website = $row['website'];
$comment = $row['comments_body'];
//build the html content to display all comments on the page if comments exist
if($id == $caid){
$displayComments .= "<ul><li><b>Posted By</b>: <span>$name</span></li><li><b>On</b>: $cmtDate</li><li><b>Website</b>: $website</li></ul><p>$comment</p>";
//display this on the html page if no comments exist
}else {
$displayComments .= "<ul><li>Sorry no comments have been posted to this article. Be the first.</li></ul>";
}
}
The "if" part of the conditional statement works but the "else part" statement doesn't display the above "No Comments" message and I get no indication of errors.
Am I going about this in the right way?
Thanks for any help.
Thanks
Gerry