Multi-level Product Tree in PHP

June 5th, 2007
by psykoprogrammer

Let us say that you wish to have multi-level display in an unordered list, much like a tree. This could be products, categories, or whatever you wish. In this example, we are going to use products with tree-like associations, and display them in an unordered list.

First, the SQL table. In this example we will use a MySQL database table called mockProducts. Here is the structure for that.

  1. CREATE TABLE `mockProducts` (
  2.   `id` int(11) NOT NULL AUTO_INCREMENT,
  3.   `parent` int(11) NOT NULL DEFAULT ‘0′,
  4.   `productName` varchar(50) DEFAULT NULL,
  5.   `price` decimal(10,0) DEFAULT NULL,
  6.   PRIMARY KEY  (`id`)
  7. ) TYPE=MyISAM;

Here is some PHP code which will construct the tree-like unordered list.

  1.   $connection = mysql_connect("mysqlserver.com", "user", "password");
  2.    mysql_select_db("someDBName");
  3.  
  4.    //————————————————————————-
  5.    // Get a listing of all the first-level products. Their parent level is set
  6.    // to zero (0).
  7.    //————————————————————————-
  8.    $productsFirstLevel = mysql_query("SELECT id, productName, price FROM mockProducts WHERE parent=0 ORDER BY productName");
  9.  
  10.    //——————————————————-
  11.    // Construct the HTML for the multi-level unordered list.
  12.    //——————————————————-
  13.    function constructTree($query, &$html)
  14.    {
  15.       while ($row = mysql_fetch_object($query))
  16.       {
  17.          $html .= sprintf("
  18.    <li>%s ($%s)</li>
  19. ", $row->productName, $row->price);
  20.          $nextQuery = mysql_query("SELECT id, productName, price FROM mockProducts WHERE parent=".$row->id." ORDER BY productName");
  21.  
  22.          if (mysql_num_rows($nextQuery) > 0)
  23.          {
  24.             $html .= "
  25. <ul>";
  26.             constructTree($nextQuery, $html);
  27.             $html .= "</ul>
  28. ";
  29.          }
  30.       }
  31.    }
  32.  
  33.    $html = "
  34. <ul>";
  35.    constructTree($productsFirstLevel, $html);
  36.    $html .= "</ul>
  37. ";
  38.  
  39.    printf("%s", $html);
  40.  
  41. ?>

Happy coding!

Comments (0)

No comments yet

Leave a Reply

You must be logged in to post a comment.