如何在循环中输出注释评论?

时间:2013-12-20 01:48:00

标签: php mysql

结构表评论:

id (int 11)
NewsIdn (varchar 10)
CommentsIdn (varchar 10) //
ForCommentsIdn (varchar 10) //have CommentsIdn comments(answers) reply to which users 
Text (varchar 100)
DateCreate (datetime)

我想为评论输出评论和评论(答案),即。页面上的结构输出数据:

-- comment 1
-----answer on comment 1
--------answer on answer on comment 1 (№1)
--------answer on answer on comment 1 (№2)
--------answer on answer on comment 1 (№3)
----------answer on answer №3 on answer on comment 1
-------------
---------------N
                       ***
                       ***
                       ***
-- comment 2
-----answer on comment 2
--------answer on answer on comment 2 (№1)
--------answer on answer on comment 2 (№2)
--------answer on answer on comment 2 (№3)
----------answer on answer №3 on answer on comment 2
-------------
---------------N

                       ***
                       ***
                       ***
-- comment N
-----answer on comment N
--------answer on answer on comment N (№1)
--------answer on answer on comment N (№2)
--------answer on answer on comment N (№3)
----------answer on answer №3 on answer on comment N

AND IE.

我得到第一条评论:

SELECT * FROM COMMENTS WHERE NewsIdn='1122121' // value NewsIdn as example

但是如何在周期中输出对评论的评论?

请告诉我怎么做?

1 个答案:

答案 0 :(得分:1)

是的,你必须要正常化...... 我为你创建了一些表格。

用户表

id(PK) name  

新闻表

id (int 11)
Text
DateCreate (datetime)
user_id(FK with user table)

评论表

id (int 11)
Text
DateCreate (datetime)
news_id(int 11)(FK with news table)
user_id

评论表的子评论

id (int 11)
comments_id(FK with comments table)
Text
user_id(int)(FK with user table)
DateCreate (datetime)

现在为每条评论写下以下查询

对于骑行,只需在注释表中使用一个循环。然后你会得到每个评论的所有答案。

$query=query("select id from news");
while($q=mysql_fetch_assoc($query)){
//Here is each news
$query1=query("SELECT comments_id,comments FROM comments c WHERE c.news_id=$q['id']");
//Here is each comment
   while($q1=mysql_fetch_assoc($query1)){
   $query2=query("
                  SELECT sub.text,u.user_name FROM sub_comments AS sub
                  LEFT JOIN comments AS c
                  ON c.id=sub.comments_id
                  INNER JOIN user AS u
                  ON u.id=sub.user_id
                  WHERE c.id=$q1['comments_id']
                 ");
                 while($q2=mysql_fetch_assoc($query2)){
                    //Here are sub comments for each comments  
                    print $q2['text'];
                 }
    }
}