tags:

views:

90

answers:

1

Okay I was wondering how can you use PHP and MySQL to create and display a side nav menu with many categories and sub-categories?

I just don't know where to begin coding the PHP code?

<ul>
   <li><a href="" title="">First Nested Link</a></li>
   <li><a href="" title="">First Nested Link</a></li>
   <li><a href="" title="">First Nested Link</a>
   <ul>
  <li><a href="" title="">Second Nested Link</a></li>
  <li><a href="" title="">Second Nested Link</a></li>
  <li><a href="" title="">Second Nested Link</a>
    <ul>
   <li><a href="" title="">Third Nested Link</a></li>
   <li><a href="" title="">Third Nested Link</a></li>
   <li><a href="" title="">Third Nested Link</a>
     <ul>
    <li><a href="" title="">Fourth Nested Link</a></li>
    <li><a href="" title="">Fourth Nested Link</a></li>
    <li><a href="" title="">Fourth Nested Link</a></li>
     </ul>
   </li>
   <li><a href="" title="">Third Nested Link</a></li>
   <li><a href="" title="">Third Nested Link</a></li>
    </ul>
  </li>
  <li><a href="" title="">Second Nested Link</a></li>
  <li><a href="" title="">Second Nested Link</a></li>
   </ul>
   </li>
   <li><a href="" title="">First Nested Link</a></li>
   <li><a href="" title="">First Nested Link</a></li>
</ul>

Here is my MySQL tables.

* categories
      id | category_name | description
* sub_categories
      id | parent_id | category_name | description
+1  A: 

You should only need one table for your categories; just set the parent_id field to null for top-level categories.

As for actually generating the HTML, you can do something along these lines (pseudocode), where $category_data is the results of the query in a two-dimensional array and $category_id is the id of the parent category being generated. To kick it off, use $category_id = 0

function print_category($category_data, $category_id)
{
    print "<ul>";
    foreach ($category_data as $category)
    {
        if ((integer)$category['parent_id'] == $category_id)
        {
            print "<li>" . $category['category_name'] . "</li>";
            print_category($category_data, $category['id']);
        }
    }
    print "</ul>";
}

You'll have to modify that for your own layout and table structure. You can improve the performance (if you have a huge number of categories) by transforming the array into a three-dimensional array, $category_data[parent_id][id][category_row].

James McNellis
Generating the faster array is actually simple enough to do it by default: `$ctg_data = array(); foreach ($rows as $row) { $ctg_data[$row['parent_id']][] = $row; }`. Then you can use `foreach ($ctg_data[$category_id] as $ctg)`.
Lukáš Lalinský