in reply to Database categories

First, I would suggest that you separate your functions so you're not trying to mix db queries with HTML presentation. I'd probably fetch the data from the db, munge the structure as needed, and then pass it to a templating system (such as HTML::Template) for display.

Recently I read a couple of articles about how to store tree structures in relational databases. Based on my browser history, they included Managing Hierarchical Data in MySQL and Storing Hierarchical Data in a Database. The latter explains both the adjacency list model (a recursion method) and the modified preorder tree traversal method. Examples of code to retrieve the tree are given for both types (but they're in php).

Finally, Wikipedia has an entry for hierarchical data model. While the content may be nothing new to you, there are several links to other resources that might be helpful.