1  <?php
 2
 3    /* 
 4    Prints the comments recursively. The only down side is that the array is
 5    potentially being traversed through each recursive call.
 6    */
 7
 8    function printNestedComment($parent, $comments_array) {
 9      foreach ($comments_array as $comment) {
10        if($parent == $comment['parent_id']) {
11          $html .= '<ul>' . "\n";
12          $html .= '<li>' . $comment['message'] . '</li>' . "\n" ;
13          $html .= printNestedComment($comment['id'], $comments_array);
14          $html .= '</ul>' . "\n";
15        }
16      }
17
18      return $html;
19    }
20
21    $host = '127.0.0.1';
22    $user = 'user';
23    $password = 'password';
24
25    $database = 'database';
26
27    $link = mysql_connect($host, $user, $password)
28            or die ('Could not connect: ' . mysql_error());
29
30    mysql_select_db($database) or die ('Could not select database');
31
32    // You should make use of prepared statements as here:
33    // http://www.databasejournal.com/features/mysql/article.php/3599166 . 
34    // I am not using it because I do not have PHP 5 installed 
35
36    // This is a convoluted example to show how to prevent SQL injections
37    // Get the parameter passed in through the URL
38    $query = sprintf("SELECT * FROM comments WHERE category='%s'",
39               mysql_real_escape_string($_REQUEST['category']));
40
41    $raw_result = mysql_query($query);
42
43    // Stick this in an array of associative arrays (hash)
44    $comments_array = Array();
45
46    while ($row = mysql_fetch_array($raw_result, MYSQL_ASSOC)) {
47      $comments_array[] = array(
48                              'id' => $row['id'],
49                              'parent_id' => $row['parent_id'],
50                              'message' => $row['message']);
51    }
52
53    // Start with the comment that has no parent (NULL parent)
54    echo printNestedComment(NULL, $comments_array);
55
56    // Free the results
57
58    mysql_free_result($raw_result);
59
60    mysql_close($link);
61
62  ?>