Creating a PHP/MySQL Tree

Discussion in 'PHP' started by xclanet, Mar 2, 2011.

  1. #1
    I was messing arround with code and i can't figure out to do this:

    http://img535.imageshack.us/i/nodetree.png/

    I have a Table in the database like this:

    CREATE TABLE IF NOT EXISTS `nodetree` (
    `node` int(11) NOT NULL,
    `prevnode` int(11) NOT NULL,
    `nextnode` int(11) NOT NULL,
    `nodename` varchar(30) NOT NULL,
    `nodelink` varchar(255) NOT NULL,
    PRIMARY KEY (`node`,`prevnode`, `nextnode`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8;

    What i want to do is to get php build that graph automatically with tables. Each node is a clickable link to node description.

    Thanks in advance.
     
    xclanet, Mar 2, 2011 IP
  2. tvoodoo

    tvoodoo Active Member

    Messages:
    239
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    53
    #2
    I think your database table structure should look something like this :
    ID : int , autoincrement
    Name : varchar
    Link : varchar
    Parent : int , can be NULL
    LevelPoz : int , NOT NULL

    Now , for the first tree node you will have Parent NULL , so you will just query to find the node(s) that have the Parent NULL :
    SELECT * FROM table WHERE Parent IS NULL

    Afterwards you will need to create a function that does this for all the children :
    SELECT * FROM table WHERE Parent = the_id_from_the_previous_Query ORDER BY LevelPoz ASC

    LevelPoz keeps the position of the node in relationship with his brothers.

    Hope that gives you what you need to code your Tree.
     
    tvoodoo, Mar 2, 2011 IP
  3. xclanet

    xclanet Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks tvoodoo for reply.

    My problem isn't the database. What i am trying to figure is how to do the php code to build the tree.

    On a simple tree, like you said, i just build a loop to parse all childrens. On this tree, i have some nodes that have childrens that are children of other nodes... and that i don't know how to figure how to do in php.

    I have tryed a simple loop that build a html table, but with that, the childrens that have 2 parents are duplicated and the branches after them too.

    I just need a php code to build a html table like that image.

    Thanks
     
    xclanet, Mar 3, 2011 IP