我有一个评论系统。每条评论都可能收到回复,而每条回复都可能收到令人厌恶的回复。
因此,我的数据库包含一个名为"comments“的表,其中包含以下重要字段:
id
text
reply_to当然,...under reply_to是回复的评论的id。
所以现在,问题很简单:我如何显示所有评论,但知道每个评论之后必须是对它的回复,每个回复之后必须是对回复的回复,等等。
我尝试的最多的,也是我不断回来的,是这样的:
$query = mysql_query("SELECT * FROM comments WHERE reply_to=0");
while ($comment = mysql_fetch_array($query))
include("comment.php");在comment.php中,我所拥有的是:
foreach ($comment as $key = $value) $$key = $value;
echo $text;
echo "<div style='margin-left:30px;'>"; //A margin for a little indent
$subquery = mysql_query("SELECT * FROM comments WHERE reply_to=$id");
while ($comment = mysql_fetch_array($subquery))
include("comment.php");
echo "</div>";但是如果我正确地重现了代码的本质,问题是:在回显第一个应答之后,它继续到第一个应答的第一个应答,然后是第一个应答的第一个应答的第一个应答,但是循环永远不会到达任何东西的第二个应答。例如,假设表格有3个评论,每个评论有3个回复,每个回复有3个回复,依此类推,上面的代码将输出:
Comment
First reply
First second-order reply
First third-order reply
...我希望我已经解释得足够清楚了。inb4:我无法向表中添加新列。
发布于 2011-08-11 12:07:04
在伪代码中:
function display_comment(comm)
echo comm's info and text
children = get children of the comment: SELECT from comments WHERE parent = (comm's id)
echo <div class="comment-thread">
foreach children as child
display_comment(comm) // notice this line
echo </div>您必须创建一个函数,以使其被递归引用。
发布于 2011-08-11 12:13:57
我通常是这样做的
function get_comments($text_id, $parent_id,$depth){
$sql="SELECT * FROM spam WHERE parent_id='".(int)$parent_id."' AND text_id='".(int)$text_id."' ";
//..query
while ($row=mysql_fetch_assoc($query)){
//some comment output use $depth*pixels to indent
$depth++;
get_comments($text_id,$row['parent_id'],$depth);
$depth--;
}
}在第一个调用中
get_comments($text_id,0,0); //发布于 2011-08-11 12:16:36
$subquery = mysql_query(SELECT * FROM comments WHERE reply_to=$comment_id);可能是什么错误。当您描述您的表定义时,字段使用comments id is namedid, but here you are usingcomment_id. Also, you are not enclosed your SQL statement in quote marks (‘'`)。是与复制粘贴相关的错误吗?
https://stackoverflow.com/questions/7020677
复制相似问题