2012-05-02 42 views
0

我有用PHP編寫的評論腳本,工作得很好。它將註釋保存在帶有紀念,主題,用戶標識和時間創建字段的mysql註釋表中。 我現在想要實現一個回覆功能。我應該創建一個新的使用用戶名,時間創建,答覆和紀念字段的答覆表。PHP/MYSQL評論 - 答覆表結構

或者只是將評論表中的回覆作爲評論添加到評論表中,但會增加兩個字段,一個表示此特定評論是回覆,另一個則表示回覆評論。

傾向於第一個選項,但它意味着額外的查詢。

希望有經驗者提出任何建議!

回答

7

我會添加兩列referenceidparentid。這樣,如果你願意,你可以嵌套評論。與在查詢中加入多個表相比,更容易,更高效。如果評論不是回覆,referenceid是0(或null)。無需創建另一列來標記它是否是答覆。

+0

你會做的註釋嵌套循環中循環的任何DIV.comment然後,您可以嵌套式的評論很簡單?還是有辦法讓他們從一個查詢中顯示 – user1260310

+0

如果是我,我會在一個MySQL語句中檢索所有數據,然後使用一些PHP邏輯和循環來嵌套。你可以在一個循環內循環,但是你要麼限制嵌套回覆的深度,要麼創建十幾個循環來支持深度嵌套的註釋。 IE:如果您發表了評論,並且我回復了您的評論,並且另一位訪問者回復了該答覆,而另一位訪問者回復了該答覆,我們已經4層 - 4圈 - 深。也許不太可能在你的實現中做得太深,但是我們是否想限制這種可能性?需要考慮的事情。 –

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.comment

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