How to create a tree view from MySQL and PHP and jquery

I need to show the tree structure of my categories stored in my mysql database.

Database Table:

table : cats:

columns : id, name, parent problem in php part:

//function to build tree menu from db table test1
function tree_set($index)
{
    global $menu;
    $q=mysql_query("select * from cats where parent='$index'");
    if(!mysql_num_rows($q))
        return;
    $menu .= '<ul>'."\n";
    while($arr=mysql_fetch_assoc($q))
    {
        $menu .= '<li>';
        $menu .= '<span class="file">'.$arr['name'].'</span>';//you can add another output there
        $menu .=tree_set("".$arr['id']."");
        $menu .= '</li>'."\n";
    }

    $menu.= '</ul>'."\n";
return $menu;

}



//variable $menu must be defined before the function call
 $menu = '
 <link rel="stylesheet" href="modules/Topics/includes/jquery.treeview.css" />
 <script src="modules/Topics/includes/lib/jquery.cookie.js" type="text/javascript"></script>
 <script src="modules/Topics/includes/jquery.treeview.js" type="text/javascript"></script>
 <script type="text/javascript" src="modules/Topics/includes/demo/demo.js"></script>
 <ul id="browser" class="filetree">'."\n";
 $menu .= tree_set(0);
 $menu .= '</ul>';
echo $menu;  

I even asked in this forum: http://forums.tizag.com/showthread.php?p=60649

The problem is in the php part of my codes that I mentioned. I can’t show the submenu, I mean, really, I don’t know how to show the submenu

Is there any chance that a php encoder will help me?

+5
source share
1 answer

, , .

, :

function tree_set($index)
{
    //global $menu; Remove this.
    $q=mysql_query("select * from cats where parent='$index'");
    if(mysql_num_rows($q) === 0)
    {
        return;
    }

    // User $tree instead of the $menu global as this way there shouldn't be any data duplication
    $tree = $index > 0 ? '<ul>' : ''; // If we are on index 0 then we don't need the enclosing ul
    while($arr=mysql_fetch_assoc($q))
    {
        $subFileCount=mysql_query("select * from cats where parent='{$arr['id']}'");
        if(mysql_num_rows($subFileCount) > 0)
        {
            $class = 'folder';
        }
        else
        {
            $class = 'file';
        }

        $tree .= '<li>';
        $tree .= '<span class="'.$class.'">'.$arr['name'].'</span>';
        $tree .=tree_set("".$arr['id']."");
        $tree .= '</li>'."\n";
    }
    $tree .= $index > 0 ? '</ul>' : ''; // If we are on index 0 then we don't need the enclosing ul

    return $tree;
}

//variable $menu must be defined before the function call
$menu = '....<ul id="browser" class="filetree">'."\n";
$menu .= tree_set(0);
$menu .= '</ul>';
echo $menu;

+3

All Articles