catandmouse
catandmouse

Reputation: 11809

if statement not working when the value is zero (PHP)

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>";
        }
    }

Upvotes: 0

Views: 1081

Answers (2)

Jonnix
Jonnix

Reputation: 4187

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

Upvotes: 0

GWW
GWW

Reputation: 44093

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.

Upvotes: 3

Related Questions