php - 如果不为空则回显相关表行 - PHP

标签 php mysql conditional-statements

我想回显 comments 表中的行,其中 entries 表上存在评论。但如果评论为空,则不显示它们。我下面的代码当前会显示对博客条目的评论,但如果为空则不会显示它们。 换句话说:博客条目和评论都会显示,但是当您回显条目但没有评论时,甚至不会回显任何内容 else 上的 echo 语句甚至不起作用。我很确定我做的这一切都是错的。我有一个代码。

//if a blog post was made
//echo all the blog post
//If you select a particular blog post
//Echo that particular blog post

if (!empty($postID)) {
  $command = "select t1.blogID t1blogID, t1.author t1author, t1.date t1date, 
             t1.entry, t2.commentID, t2.author t2author, t2.date t2date, 
             t2.comments from $table_name t1, $table_name2 t2 
             where t1.blogID = t2.blogID and t1.blogID = $postID";
  $result = $db->query($command);
while ($data = $result->fetch_object()) {
  // I figured I'd create a variable here
  $postID = $data->t1blogID; 
  $t1author = $data->t1author;
  $t1date = $data->t1date;
  $entry = $data->entry;
  $commentID = $data->commentID;
  $t2author = $data->t2author;
  $t2date = $data->t2date;
  $comments = $data->comments;

  //So I can create this conditional statement 
  // if there is no comment
  if (!empty($commentID)) {
   echo "<TR><TD>Blog ID ".$postID."</TD>";
   echo "<TD>".$t1author."</TD>";
    echo "<TD>".$t1date."</TD>";
    echo "<TD>".$entry."</TD></TR>\n";   
    echo "<TR><TD>Comment ID ".$commentID."</TD>";
    echo "<TD>".$t2author."</TD>";
    echo "<TD>".$t2date."</TD>";
    echo "<TD>".$comments."</TD></TR>\n";
  }
  else {
    echo "<TR><TD>Blog ID ".$postID."</TD>";
    echo "<TD>".$t1author."</TD>";
    echo "<TD>".$t1date."</TD>";
    echo "<TD>".$entry."</TD></TR>\n";     
  }
  }
result->free();

最佳答案

尝试左连接两个表:

select t1.blogID t1blogID, t1.author t1author, t1.date t1date, t1.entry, t2.commentID, t2.author t2author, t2.date t2date, t2.comments from $table_name t1 LEFT JOIN $table_name2 t2 ON t1.blogID = t2.blogID where t1.blogID = $postID

可以。

关于php - 如果不为空则回显相关表行 - PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20707790/

相关文章:

mysql - Where 子句未按预期工作 : I get data from 2 different IDs when only one is specified

c - 如何在C编程中获得以下输出

python - python中的条件矩阵运算

php - 从 PHPWord 生成的 .docx 生成 PDF

mysql - 如何在 shell 脚本文件的 MySQL 查询中嵌入 BASH 变量

PHPExcel - Excel 报告生成期间的数据填充不正确

mysql "IN"条件与子查询

php - Symfony2 - Twig 更新未渲染

php - 比较 php 数组和 mysql 列

php - Yii2 ajax 错误请求 (#400)