如果没有注释,则显示"be the first to comment on a post"消息 PHP MySQLI



我这里有一个代码,但似乎无法让它工作。如果没有人对该用户发布的评论,我想显示一条消息,例如"成为第一个发表评论的人"。我的代码如下:

<?php 
$comment_query = mysqli_query($con,"SELECT * ,UNIX_TIMESTAMP() - date_posted AS TimeSpent FROM comment LEFT JOIN users on users.id = comment.user_id where post_id = '$id'") or die (mysqli_error());
while ($comment_row=mysqli_fetch_array($comment_query)){
$comment_id = $comment_row['comment_id'];
$comment_by = $comment_row['name'];
if($id == $id && $comment_row['content']=""){
$beFirst = "Be the first to comment";
} else {
$beFirst = $comment_row['content'];
}
?>
<br><img src='<?= $user_form_img; ?>' height=24px width=24px align=left style="display:inline-block"/><p style="padding-left:24px;"><a href="#"><?php echo $comment_by; ?></a><br/><font style=font-size:18px;><?php echo $comment_row['content']; ?><?= $beFirst; ?>
</font><br>
<?php               
$days = floor($comment_row['TimeSpent'] / (60 * 60 * 24));
$remainder = $comment_row['TimeSpent'] % (60 * 60 * 24);
$hours = floor($remainder / (60 * 60));
$remainder = $remainder % (60 * 60);
$minutes = floor($remainder / 60);
$seconds = $remainder % 60;
if($days > 0)
echo date('F d, Y - H:i:sa', $comment_row['date_posted']);
elseif($days == 0 && $hours == 0 && $minutes == 0)
echo "A few seconds ago";       
elseif($days == 0 && $hours == 0)
echo $minutes.' minutes ago';
?>

任何帮助将不胜感激。

您需要替换此检查:

if($id == $id && $comment_row['content']=""){

if ($comment_row['content'] == '') {

因为使用$comment_row['content']="",您将一个空值分配给变量,在这种情况下将false布尔值。$id == $id总是true.

所以if($id == $id && $comment_row['content']=""){会被解释为if (true && false),这总是false.

此外,最好将变量命名为$beFirst,例如,作为$commentMsg。因为主值将是注释的文本,而不是默认文本("成为第一个评论的人")。或者只是不要创建变量并使用三元运算符:

<?= ($comment_row['content'] == '') ? "Be the first to comment" : $comment_row['content'] ?>

此外,我强烈建议使用 PHP PDO 准备语句来防止 SQL 注入。

最新更新