title: Displaying comments related to posts using PHP & MySQL
body: <p>I have a page that displays all posts related to category X. I'm having trouble displaying the comments related to each post.</p>
  
  <p>Here are the relevant database tables:</p>
  
  <pre><code>TABLE 'articles'
  'article_id'
  'title'
  'article'
  'updated'
  'created'
  
  TABLE 'categories'
  'cat_id'
  'category'
  
  TABLE 'article2cat' (relates an article to a category using two primary keys)
  article_id
  cat_id
  
  TABLE 'comments'
  comment_id
  comment
  user
  created
  
  TABLE 'comment2article' relates a comment to an article using two primary keys)
  comment_id
  article_d
  </code></pre>
  
  <p>The SQL query that pulls up the articles and comments is:</p>
  
  <pre><code>SELECT articles.article_id, articles.title, articles.article, DATE_FORMAT(articles.created, "%b, %Y") AS date_created, comments.comment_id, comments.user, comments.comment 
  FROM articles INNER JOIN article2cat USING (article_id), comments INNER JOIN comment2article USING (comment_id)
  WHERE cat_id=4
  ORDER BY articles.created DESC;
  </code></pre>
  
  <p>The code that displays the articles and comments is:</p>
  
  <pre><code>&lt;table id="articles-table" cellpadding="0" cellspacing="0"&gt;
      &lt;?php while ($row = $result-&gt;fetch_assoc()) { ?&gt;
      &lt;tr&gt;
          &lt;td id="articles-article"&gt;
              &lt;div id="articles-article-internal"&gt;
                  &lt;?php echo format($row['article']); ?&gt;&lt;/div&gt;
          &lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;&lt;?php echo $row['comment']; ?&gt;&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;&amp;nbsp;&lt;/td&gt;
      &lt;/tr&gt;
      &lt;?php } ?&gt;
  &lt;/table&gt;
  </code></pre>
  
  <p><strong>The problem is when I try to echo out only the comments related to a given post/article. At the moment it's displaying all comments regardless of the post they belong to.</strong> </p>
  
  <p>I found several similar questions on StackOverflow, but none that I was able to use to resolve my problem.</p>