tags:

views:

28

answers:

1

I'm trying to make a hierarchical list with PHP and an SQLite table setup like this:

    |   itemid  |   parentid    |   name    |
    -----------------------------------------
    |   1       |   null        |   Item1   |
    |   2       |   null        |   Item2   |
    |   3       |   1           |   Item3   |
    |   4       |   1           |   Item4   |
    |   5       |   2           |   Item5   |
    |   6       |   5           |   Item6   |

The lists would be built with unordered lists and allow for this type of tree structure:

Item1
    |_Item3
    |_Item4
Item2
    |_Item5
        |_Item6

I've seen this done with directories and flat arrays, but I can't seem to make it work right with this structure and without a depth limit.

+2  A: 

You're using a textbook design for storing hierarchical data in an SQL database. This design is called Adjacency List, i.e. each node in the hierarchy has a parentid foreign key to its immediate parent.

With this design, you can't generate a tree like you describe and support arbitrary depth for the tree. You've already figured this out.

Most other SQL databases (PostgreSQL, Microsoft, Oracle, IBM DB2) support recursive queries, which solve this problem. But SQLite and MySQL don't support this feature of SQL yet.

So you need another solution to store the hierarchy. There are several solutions for this. See my presentation Models for Hierarchical Data with PHP and MySQL for descriptions and examples.

I usually prefer a design I call Closure Table, but each design has strength and weaknesses. Which one is best for your project depends on what kinds of queries you need to do efficiently with your data. So you should go study the solutions and choose one for yourself.

Bill Karwin
Thank you for the information. Exactly what I needed.
syllabic