【问题标题】:PHP MYSQL showing posts with commentsPHP MYSQL 显示带有评论的帖子
【发布时间】:2011-06-30 20:30:03
【问题描述】:

我不知道从哪里开始,让我简单点......

我有 2 个表帖子和 cmets,帖子包含 2 个字段:idpost_name,而 cmets 包含 3 个字段:idcommentpost_id。我有一些帖子,其中很少有 cmets。

如何使用 while 循环显示所有带有相关 cmets 的帖子?

提前谢谢....

【问题讨论】:

  • 嗨,我很好奇,在这种情况下,我怎么能同时更新它们,这让我发疯了?

标签: php mysql


【解决方案1】:
   SELECT `p`.`post_name`, `c`.`comment`
     FROM `posts` AS `p`
          JOIN `comments` AS `c` ON(`p`.`id` = `c`.`post_id`)
GROUP BY  `p`.`id`;

这将为您提供一个结果集,其中每一行都包含一条评论以及与该评论相关的帖子的名称。

【讨论】:

    【解决方案2】:

    您需要一个嵌套循环来完成您要查找的内容。这是一个可以帮助您入门的示例。

    $posts_result = mysql_query("SELECT your, columns FROM poststable");
    if(mysql_num_rows($posts_result) > 0){
        $comments_result = mysql_query("SELECT comments FROM commentstable WHERE comments.post_id = $post_id");
        while($post = mysql_fetch_array($posts_result){
            // print post details
    
            if(mysql_num_rows($comments_result) > 0){
                while($comment = mysql_fetch_array($comments_result)) {
                    // print comment details
                }
            } else {
                // print comments default for when there are no comments
            }
        } // End posts while
    } else {
        // print no posts found
    }
    

    【讨论】:

    • 嵌套循环是在这里提供所需功能的最简单方法,它回答了 OP 关于如何在 while 循环中执行此操作的问题。
    【解决方案3】:

    运行查询

    select * from posts p, comments c where p.id=c.post_id group by p.id;
    

    并遍历结果并根据需要显示它们。

    【讨论】:

      【解决方案4】:

      这应该让你开始:

      $sql = 'SELECT c.*, p.post_name FROM posts p INNER JOIN comments c ON p.id = c.post_id ORDER BY p.id DESC, c.post_id DESC';
      $result = mysql_query($sql);
      $previous_post = 0;
      while ($data = mysql_fetch_assoc($result)) {
          if ($previous_post != $data['post_id']) {
              echo '<h1>' . $data['post_name'] . '</h1>';
              $previous_post = $data['post_id'];
          }
          echo '<p>' . $data['comment'] . '</p>';
      }
      

      【讨论】:

        猜你喜欢
        • 2012-05-02
        • 1970-01-01
        • 1970-01-01
        • 2012-07-20
        • 1970-01-01
        • 2015-03-04
        • 2019-04-12
        • 2019-08-24
        • 1970-01-01
        相关资源
        最近更新 更多