How to Create Dynamic Tree View Menu

In this tutorial, I will describe how to create dynamic tree view menu using PHP, MySQL and css. It’s very common functionality in any web project, I have seen a lot of code sample through goggling and I have created treeview menu based on search.

Actually, I need to create a task list tree view menu based on project task. A single task may be divided number of subtask, So I need to add dynamically sub-task into task tree and meanwhile time its reflect into tree view.

You can also checkout other tutorial of TreeView Menu,

Create Dynamically Treeview Menu Using PHP & MySQL

Let’s create treeview based on MySQL and css. We will create database table which hold all the tree menu information.

Step 1- Create MySQL table

First, we will Create treeview table in MySQL database. this table contains four column-

  • id – This table field hold the task id.
  • title – This column will hold the menu title.
  • parent_id – This column will use to store parent id of menu and name is the task name.

Step 2: Created index.php file and created createTreeView() method. This method is recursive if current task id is greater than prev task id.

Step 3: Add below code into index.php file to display tree view menu.This is main file of treeview example, Here we will call createTreeView() method with required parameters.

Step 4: Let’s create a style.css CSS file, This file contains all css related classes with in it, Currently I am using order list to create tree view. You can also change image path here as per your image location.

Result:

Demo and Download Source Code

117 thoughts on “How to Create Dynamic Tree View Menu

  1. Hi Parverz can you send me the complete source code of
    How to Create Dynamic Tree View Menu
    because i couldn’t run this,thanks

  2. Please could create a treeview based on this table, and the table indicador would be the first person and below them show the name of the person who registered through the indicador

    • you can enter person(A) name under ‘name’ column. if it has registered persons(B) sets parent id 0 for A person and set perant id od A person to B member.

  3. i see your code this is very good effort but i want to make dynamic tree having 2 childs for example 2/2 tree where a parent has two child and so on plz if you help me i am thankful to you
    best regards

  4. Do you have any idea if we want to do the same work but the hierarchy is divided in multiple in many records.
    something like that :
    ————————————————————————-
    Level1 level2 level3 level4
    ————————————————————————-

    for each level1 there is one or more corresponding from the level2 and so on for the rest (level3 and level4)

    thanks

  5. Hi, I have just tested your menu and it works great so far. Thank you for that.
    But I have a question: is it possible to put a text field after each label for tag?
    I would like to use this to fill a mysql datadase with it.

    Thanks in advance

    Anton

  6. Hi, I could not run the codes, I’m beginner in php and I don’t know what is the problem. These are my errors:

    Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/TestFolder/treeview/treeview.php on line 14

    Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/TestFolder/treeview/treeview.php on line 65

    Could you help me please.
    Thank you.

    • Hi,
      You have error on ‘while($row = mysql_fetch_assoc($result)’ line.You have passed $result as Boolean instead of resource.

      Have you cheked below query:
      $qry=”SELECT * FROM treeview_items”;
      $result=mysql_query($qry);

      Please varify $results contains data.

      • Thank you for your reply, No. I did not add/change anything; I just download your codes and run on my laptop. I expected to see the same result as yours. (your screenshop).

        Do I need to do something?

  7. it works…
    but… how and where i put my url or links…
    and when i click menu (task3), (task1) expand.??
    would you help me..??

  8. I’m having trouble with $arrayCategories[$row[‘id’]] = array(“parent_id” => $row[‘parent_id’], “name” =>

    [‘id’] ?

    can you help me please,
    thxs

  9. When I used this code, my check-box is located on the next line instead of inline with the folder icon. Although, I need to click above the box to expand and contract the tree branch. How do I move the check box up as is displayed in your picture example?

    Thank you.

  10. Parvez,

    Thank you for the quick reply. I’m really new to the PHP and CSS world. How can I make this open into a new window all together instead of being inside an existing frame on my web-site?

    Thanks again,
    Victor

  11. Ok it’s work i add some query like this:
    $sql=SELECT
    id,
    pid As parent_id,
    pn As parent_name,
    GROUP_CONCAT(cn separator ‘, ‘) child_name
    FROM my_tbl
    WHERE
    GROUP BY parent_name
    ORDER BY parent_id
    but how can i click to target_url that i want?

    thxs anyway

  12. Hello
    I like very much your tree view.
    Do you know if there is a way to capture the event when selectin one of the node?
    How?
    Thanks

  13. hi Parvez
    it is very useful for me.
    and my requirement is when i click on sub menu it should be highlighted and stay there.
    it should not be collapse.

  14. Hi Parvez

    Thanks in advance.
    i am new to php. and i am not having knowledge of jquey,
    please me the modified code to my email.
    thank you..

  15. Hi Parvez

    This is a great example and works very well. The only thing I am struggling with is how to capture which node a user has selected do you have any extended examples on how to do this?

    Thanks again.

    • Hi Stephen,
      Thanks,I have an idea for your problem,You can add an attribute on each node which value would be node name, Now you need to capture on click event with jquery and get node name.

      Thanks
      Parvez Alam

  16. Hi Parvez
    This is a very good example but if you click on any task(not on plus and minus) resulting the collapse and expand the first root task.
    How can we fix this?
    thanks in advance

  17. Dear Parvez.
    I am a cut paste master, not a programmer. The code works perfectly on my machine. However, is it possible to add a context menu which when right clicked on a particular node , allows adding, editing and deleting a node. And yes, contents of the field in a new window. No idea about anchor tag. Is this what was meant. Subfile 1
    Doesn’t work .

    Your help is required.

    Rajeev.

    • Hi rajeev,
      You need to change as below for anchor tag.
      ‘.$category[‘name’].’

      for context menu you need to create ur own or can use any jquery plugin for this.

  18. hi, my question is

    in this line $qry=”SELECT * FROM treeview_items”;

    if i want something like this —— $qry=”SELECT * FROM treeview_items where id = 3″;

    and the tree start in task3 and retrive the childrens having in the parent_id 3 recursive

  19. Sir, I want replace the folder icon with check box option. But i am not able to do that. It doesn’t display that.

  20. Hi Parvez I apply the tree view in my website but now i need to give drag and drop facility in it
    can you guide me for that how can i do it
    Thanks

  21. Sir I have another doubt,
    Display the details of the form like grid in the same page and we can edit and delete details in the same page.

  22. good work ,I need help to display the tree from right to left please
    I can not do that when I am trying the layout differ

  23. This is a very good example but I need help to display the treeview
    $qry=”SELECT * FROM data WHERE rfid or myid=’$id’ “;

    not work single tree?

  24. Sir, your code was very helpful but instead of the folder image the id is displaying which is given in the database at the time of inserting .
    Please help!!!!!!!!!!!!!

      • Sir i have solved the issue, thank you very much .
        How do i put check box for each folder because depending on the ticks in the check box i am going to construct a pivot table

          • Sorry sir, I am very new to php. Apologies for my repeated queries, the checkbox seem to display but i cannot tick them. It would be helpful if you tell me css part to make it work. Thanks a million in advance.

  25. This is a very good example
    SELECT * FROM treeview_items WHERE parent_id or id=’3′
    parent id “0” if the tree view , showing
    but
    SELECT * FROM treeview_items WHERE parent_id or id=’5′
    parent id “5” if the tree view is not showing
    pls help

  26. Hello,

    Thanks for the script.

    I would like to put it horizontaly, and put some extra , like admin
    how to make that?
    Thanks

    • Do You want tree view horizontally, you can handle using CSS.The best way like wordpress admin menu you can create using bootstrap3 easily.

  27. Hi Parvez,

    Thanks for this beautiful script. I am newly working with jstree concept.
    I have done with tree view by fetching data from database and converting it to json and drag and drop also working fine.

    But I the create delete and rename concept is not working properly. And I am also not getting how to update it in database after creating or deleting any node from a particular tree.
    Can you please help with this. Please post some tutorial regarding to this. I really need it.

    Thank You So much
    Srustita.

  28. hi, how make link page for each node… Example: I use this dynacmic tree, but When I click any one folder, I should be directed to another php page OR make appear another php page on same page. Can anyone please give details. Thanks in Advance… 🙂

  29. You just need to generate json data structure as mentioned in post then you return this json from controller action to view file and render that on div.

  30. thank’s a lot for this code. i added some stuff like picture and more options. if it can help some one !

    function createTreeView($array, $currentParent, $currLevel = 0, $prevLevel = -1)
    {
    global $module_folder;
    global $page_name;
    global $modify_lang;
    global $common_picture_show;

    foreach ($array as $categoryId => $don_1)
    {
    if ($currentParent == $don_1[‘id_parent’])
    {
    if ($currLevel > $prevLevel) echo ” “;
    if ($currLevel == $prevLevel) echo ” “;
    echo
    “”
    .”“.$modify_lang.”
    .” > ”
    .””.$common_picture_show.””
    .”“.$don_1[‘title’].”“;
    if ($currLevel > $prevLevel)
    {
    $prevLevel = $currLevel;
    }
    $currLevel++;
    createTreeView ($array, $categoryId, $currLevel, $prevLevel);
    $currLevel–;
    }
    }
    if ($currLevel == $prevLevel) echo ” “;
    }
    $rep_1 = mysqli_query($connexion, ‘SELECT * FROM model3_categorys’);
    $arrayCategories = array();
    while($don_1 = mysqli_fetch_assoc($rep_1))
    {
    $common_picture=””.$page_name.”_list”;include(“../common/scripts/common_picture.php”);
    $arrayCategories[$don_1[‘id’]] = array(“id_parent” => $don_1[‘id_parent’], “title” => $don_1[‘title’], “id” => $don_1[‘id’], “picture” => $don_1[‘picture’]);
    }
    if(mysqli_num_rows($rep_1)!=0)
    {
    createTreeView($arrayCategories, 0);
    }

Comments are closed.