PHP / MYSQL评论 - 回复表结构

时间:2012-05-02 01:55:10

标签: php mysql comments

我有一个用PHP编写的评论脚本,效果很好。它将注释保存在一个mysql注释表中,其中包含commentid,subjectid,userid和timecreated的字段。 我现在想要实现一个回复功能。我应该创建一个新的回复表,其中包含用户ID,时间创建,回复和纪念字段。

或者最好只在评论表中包含回复作为评论,但有两个额外字段,一个表示此特定评论是回复,另一个表示评论是回复。

倾向于第一个选项,但这意味着额外的查询。

非常感谢有经验的人提出的建议!

2 个答案:

答案 0 :(得分:7)

我会为referenceidparentid添加两列。这样,如果您愿意,可以使用嵌套注释。比在查询中连接多个表更容易,更有效。如果评论不是回复,则referenceid为0(或为空)。无需创建另一列来标记它是否是回复。

答案 1 :(得分:5)

这不是原始问题的答案,但我确实希望向您展示一种快速而肮脏的方法来嵌套注释,如果这是我的项目,我会使用它。几乎肯定有更优雅的方法,这里的另一个成员可能有建议。

<?php

// Retrieve ALL comments related to this subject (including all replies and nested comments)
$rs = mysql_query( 'SELECT * FROM `comments` WHERE subjectid = '7' ORDER BY timecreated ASC' );

// Process ALL comments and place them into an array based on their parent id
// Thus we end up with something like:
// $data[ 0 ][ 0 ] = array( 'commentid' => 1, 'subjectid' => 7, 'userid' => 1, 'timecreated' => '2012-05-01 12:00:00', 'parentid' => 0 );
// $data[ 0 ][ 1 ] = array( 'commentid' => 2, 'subjectid' => 7, 'userid' => 5, 'timecreated' => '2012-05-01 14:00:00', 'parentid' => 0 );
// $data[ 2 ][ 0 ] = array( 'commentid' => 3, 'subjectid' => 7, 'userid' => 1, 'timecreated' => '2012-05-01 16:00:00', 'parentid' => 2 ); This is a reply to commentid #2
// $data[ 2 ][ 1 ] = array( 'commentid' => 4, 'subjectid' => 7, 'userid' => 5, 'timecreated' => '2012-05-01 16:30:00', 'parentid' => 2 ); This is another reply to commentid #2
// $data[ 3 ][ 0 ] = array( 'commentid' => 5, 'subjectid' => 7, 'userid' => 3, 'timecreated' => '2012-05-01 17:00:00', 'parentid' => 3 ); This is a reply to the reply with commentid #3

while ( $row = mysql_fetch_assoc( $rs ) ){
    $data[ $row['parentid'] ][] = $row;
}

function output_comments( &$data_array, $parentid ){

    // Loop through all comments with matching $parentid

    foreach ( $data_array[ $parentid ] as $k=>$v ){
        // Output all comments, open .comment DIV but do not close (for nesting purposes)
        echo '<div class="comment"><strong>' . $v['username'] . ':</strong> ' . $v['message'];

        // If there are any replies to this comment, output them by recursively calling this function
        if ( count( $data_array[ $v['commentid'] ] > 0 ){
            output_comments( $data_array, $v['commentid'] );
        }

        // Close the open DIV
        echo '</div>';
    }
}


// Call the output_comments() function, which will recursively run to support unlimited nesting

output_comments( $data, 0 );

然后,您可以通过缩进任何拥有父DIV.com的DIV.com来轻松设置嵌套注释的样式

<style type="text/css">
.comment .comment {
    padding-left: 30px;
}
</style>