显示PHP / mySQL站点中每个帖子的注释

时间:2016-12-22 16:40:15

标签: php mysql

我正在尝试显示多个帖子,每个帖子都有自己的多条评论。下面的内容适用于第一篇文章(或至少显示3条评论中的2条),但其余部分则不适用。我搜索但无法在本网站或其他地方找到(或无法识别)这个确切问题的答案。感谢。

$result1 = @mysql_query('select * from posts,comments where comment_post_ID = ID and post_status="publish" and comment_approved="1" ORDER BY post_date,category,subcat1,subcat2 ASC');
$result2 = @mysql_query('select * from comments where comment_approved="1" ORDER BY comment_date');
$row = mysql_fetch_array($result1);
$row2 = mysql_fetch_array($result2);
while ($row = mysql_fetch_array($result1)) {
    $post = $row['post_content'];
    $id = $row['ID'];
    $title = $row['post_title'];
    $content = "<br /><h3 align=\"left\">" . $title . "</h3>\n";
    $content .= "<h4 align=\"left\">by " . $row['post_author'] . " - " . $row['post_date'] . "</h4>\n";
    $content .= "<p align=\"left\">" . var_export($post, true) . "</p>\n<p>\n";
    echo $content; 
    while ($row2 = mysql_fetch_array($result2)) {
            $comment = "<blockquote>";
            $comment .= "<h4 align=\"left\">" . $row2['comment_author'] . " commented on " . $row2['comment_date'] . "</h4>\n";
            $comment .= "<p align=\"left\">" . $row2['comment_content'] . "</p>\n<p>\n";
            $comment .= "</blockquote>";
            if($row2['comment_post_ID'] == $id) {
                echo $comment;
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

下面,这终于按预期工作了:

    $postData = mysqli_query($conn,"SELECT * FROM wp_posts ORDER BY post_date ASC) or die(mysqli_error()); 
    $commentData = mysqli_query($conn,"SELECT * FROM wp_comments WHERE comment_approved = '1' ORDER BY comment_date ASC") or die(mysqli_error()); 
    $posts = array();     
    while($row = mysqli_fetch_assoc($postData)) {
        $posts[] = $row; 
        $commentrow = mysqli_fetch_assoc($commentData);
        $comments[] = $commentrow; 
        echo '<h3>' . $row['post_title'] . '</h3>';
        echo '<h5>' . $row['post_author'] . ', ' . $row['post_date'] . '</h5>';
        echo '<p>' . $row['post_excerpt'] . '... <a href="' . $row['permalink'] . '">read more</a></p>';
        if($row['comment_count'] > 0) {
            echo '<blockquote>';
            echo '<b>Comments</b><br />';
            foreach($comments as $comment) {
                if($row['ID']==$comment['comment_post_ID']) {
                    $comment_excerpt = substr($comment['comment_content'],0,100);
                    echo '<br>' . $comment_excerpt . ' - <b>' . $comment['comment_author'] . '</b>, ' . $comment['comment_date'] . '<br>'; 
                    }
                }            
            echo '</blockquote>';
            }
        }