views:

853

answers:

2

Hello, 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.

+3  A: 

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

Jamie Lewis
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
A: 

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