PHP MYSQL showing posts with comments

I dont know where to start let me make it simple...

I have 2 tables posts and comments, posts consisting 2 fields: id and post_name and comments consisting of 3 fields: id, comment and post_id. I have some posts with few comments on those.

How can I display all posts with the related comments using while loop?

Thanks in advance....

Answer #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`;

This will give you a resultset where each row contains a comment and the name of the post that goes with that comment.

Answer #2:

You'll need a nested loop to accomplish what you are looking for. Here's a sample that should help get you started.

$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
Answered By: KyleWpppd

Answer #3:

Run query

select * from posts p, comments c where group by;

and iterate over the results and display them as you want.

Answered By: Zimbabao

Answer #4:

This should get you started:

$sql = 'SELECT c.*, p.post_name FROM posts p INNER JOIN comments c ON = c.post_id ORDER BY 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>';
Answered By: Dave Child
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

# More Articles