当值为零时if语句不工作(PHP)

时间:2011-09-12 14:38:04

标签: php if-statement

如果我将if($comments_count == 0)更改为if($comments_count == 1),则会回显文本(如果有1条评论)。但是回到== 0,命令不会被执行。我尝试在没有评论的页面上回显$ comments_count的值并且它显示为0.但if-else忽略它并且不打印任何内容。

这是代码:

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

2 个答案:

答案 0 :(得分:3)

您需要将if语句移出while循环。由于行数为0,mysql_fetch_array调用不会返回结果,并且不会执行内部循环代码。

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(....){
    }
}

作为旁注,如果你真的可以切换到使用prepared语句和mysqli,或者至少使用mysql_real_escape_string来转义输入以防止SQL注入攻击。

答案 1 :(得分:0)

可能因为如果没有行,mysql_fetch_array将返回false。