0

I've got a menu, that is something like this:

<ul id="menu_cat">
    <li><a class="cat1" href="#">category 1</a>
    <ul>
    <li><a class="cat2" href="#">category 2</a>
        <ul>
            <li><a class="cat3" href="#">category 3</a></li>
            <li><a class="cat3" href="#">category 3</a></li>
            <li><a class="cat3" href="#">category 3</a></li>
        </ul>       
    </li>
    <li><a class="cat2" href="#">Category 2</a>
        <ul>
            <li><a class="cat3" href="#">category 3</a></li>
            <li><a class="cat3" href="#">category 3</a></li>
            <li><a class="cat3" href="#">category 3</a></li>
        </ul>
    </li>
    <li><a class="cat2" href="#">Category 2</a>
        <ul>
            <li><a class="cat3" href="#">Category 3</a></li>
            <li><a class="cat3" href="#">category 3</a></li>
            <li><a class="cat3" href="#">category 3</a></li>
        </ul> 
    </li>
    </ul> <!-- End of CAT1-->
    </li> <!-- End of .Krmiva -->
</ul>

Now I need to make it dynamic, so the "Category 1, 2, 3" are taken from MySQL database, but I canť think of any other solution than making it something like 3 tables for CAT1, CAT2, CAT3 and than for every item in CAT1, selecting submenus from CAT2 and for every CAT2 selecting submenus from CAT3 ... which would mean to make like 20 SELECT * FROM queries.

Any idea? Thanks, Mike.

krs
  • 4,096
  • 19
  • 22
Mike
  • 6,854
  • 17
  • 53
  • 68
  • 2
    Partial duplicate of this: http://stackoverflow.com/questions/1450405/php-tutorial-to-build-browse-and-link-categories-and-sub-categories/1450409 – Eimantas Sep 20 '09 at 11:06

2 Answers2

3

Your best bet is to just have a Category table, which includes a field "Parent", then all you have to do is recursively select each Category based on its parent.

So, first find the first category without any parents (or a root parent 0), then select the first category that has the previous category as a parent. And so on until the category you are on has no children, then backtrack through the table repeating the process.

The site point articles linked to in Eimantas' comment gives a very detailed outline of this: Storing Hierarchical Data in a Database

Svante
  • 50,694
  • 11
  • 78
  • 122
AAA
  • 4,928
  • 1
  • 24
  • 20
  • 1
    More links for hierarchical data in mysql: http://dev.mysql.com/tech-resources/articles/hierarchical-data.html, http://stackoverflow.com/questions/1271124/does-mysql-5-have-procedures-for-managing-hierarchical-data – txyoji Sep 20 '09 at 12:44
  • link to answer that shows a working recursive PHP function (with mysql mixed in): http://stackoverflow.com/a/15309305/631764 – Buttle Butkus Mar 09 '13 at 10:16
0

Yes, Jamie has given right thing. you can maintain in database that way or another alternative. you can prepare recursive loop for the same.

if its 2 level, i think, it will work well, but for multiple hierarchy you need adjust your css.

santosh
  • 132
  • 2
  • 2
  • 5