当值为零时 if 语句不起作用 (PHP)
如果我将 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>";
}
}
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>";
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要将 if 语句移出 while 循环。由于行数为 0,mysql_fetch_array 调用将不会返回结果,并且内部 while 循环代码将不会被执行。
作为旁注,如果可以的话,您确实应该切换到使用 prepared 语句和 mysqli 或至少使用
mysql_real_escape_string
转义您的输入以防止SQL注入攻击。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.
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.可能是因为如果没有行 mysql_fetch_array 将返回 false。
Probably because if there are no rows mysql_fetch_array will return false.