0

If I change if($comments_count == 0) to if($comments_count == 1), it echoes out the text (if there is 1 comment). But revert back to == 0, the command doesn't get executed. I tried echoing out the value of $comments_count on a page that doesn't have a comment and it says 0. But the if-else ignores it and doesn't print out anything.

This is the code:

$query = "SELECT * FROM comments WHERE id = {$set_id}";
    $all_comments_set = mysql_query($query); 
    $comments_count = mysql_num_rows($all_comments_set);

    while($comment = mysql_fetch_array($all_comments_set)) {
        if($comments_count == 0) {
            echo $comments_count;
            echo "<div class='comments'><p>There are no comments to show right now. Be the first to comment!</p></div>";
        } else {
            echo $comments_count;   
            echo "<div class='comments'>
                <p class='commenter'><a href=''>".$comment['commentAuthor']."</a></p>
                <p>".$comment['comment']."</p>
              </div>";
        }
    }
1
  • 1
    Surely you don't want to iterate through that while loop if you already know you have no comments? Commented Sep 12, 2011 at 14:40

2 Answers 2

3

You need to move the if statement out of the while loop. Since the number of rows is 0 the mysql_fetch_array call will not return a result and the inner-while loop code will not be executed.

if($comments_count == 0) {
        echo $comments_count;
        echo "<div class='comments'><p>There are no comments to show right now. Be the first to comment!</p></div>";
} else {
    while(....){
    }
}

As a side note if you can you really should switch to using prepared statements and mysqli or at least escape your input using mysql_real_escape_string to prevent SQL injection attacks.

Sign up to request clarification or add additional context in comments.

Comments

0

Probably because if there are no rows mysql_fetch_array will return false.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.