PHP/MYSQL 注释-回复表结构


PHP/MYSQL Comment-reply table structure

我有一个用PHP编写的注释脚本,工作得很好。 它将注释保存在mysql注释表中,其中包含注释ID,主题ID,用户ID和时间创建的字段。我现在想实现一个回复功能。 我是否应该创建一个包含用户 id、创建时间、回复和注释 id 字段的新回复表。

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

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

希望有经验的人有任何建议!

我会为referenceidparentid添加两列。这样,如果您愿意,可以拥有嵌套注释。比在查询中联接多个表要容易得多,效率也高得多。如果注释不是回复,则referenceid为 0(或 null)。无需创建另一列来标记它是否为回复。

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

<?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.comment 的任何 DIV.comment 来非常简单地设置嵌套注释的样式

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