How to make a tree view from MySQL and PHP and jquery - php

i need to show a treeview of my categories , saved in my mysql database .
Database table :
table : cats :
columns: id,name,parent
problem is 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
problem is in php part of my codes that i mentioned . i cant show sub menus , i mean , really i dont know how to show sub menus
is there any chance of a pro php coder helping me here ?

It looks like you are sending duplicate data to your menu variable, which doesn't need to be there.
I would change your function to do this:
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;
updated based on comments on question

Related

Mega dropdown menu css for mysql database data

I want to make mega dropdown menu that comes from mysql database. Below is my php code. The code is working well. But the problem is I am unable to make mega dropdown menu for the code below.
I need the mega menu like the example here : https://bootsnipp.com/snippets/featured/bootstrap-mega-menu
My problem is how will I make more div with the below php code .
Plz help me the css for the mega drop down menu as shown above.
<?php
$sql = "SELECT id, product, parent_id, category_link FROM category ORDER BY parent_id, id";
$results = mysqli_query($conn,$sql) or die(mysqli_error()) ;
if($results)
{
while($result = mysqli_fetch_array($results))
{
$category['categories'][$result['id']] = $result;
$category['parent_cats'][$result['parent_id']][] = $result['id'];
}
}
function getCategories($parent, $category)
{
$html = "";
if (isset($category['parent_cats'][$parent]))
{
$html .= "<div id='wrapper'>";
$html .= "<ul class='mega-menu'>\n";
foreach ($category['parent_cats'][$parent] as $cat_id)
{
if (!isset($category['parent_cats'][$cat_id]))
{
$html .= "<li class='mega-menu-drop'>\n <a class='mega-menu-content' href='" . $category['categories'][$cat_id]['category_link'] . "'>" . $category['categories'][$cat_id]['product'] . "</a>\n</li> \n";
}
if (isset($category['parent_cats'][$cat_id]))
{
$html .= "<li class='mega-menu-drop'>\n <a class='mega-menu-content' href='" . $category['categories'][$cat_id]['category_link'] . "'>" . $category['categories'][$cat_id]['product'] . "</a> \n";
$html .= getCategories($cat_id, $category);
$html .= "</li> \n";
}
}
$html .= "</ul> \n";
$html .= "</div>";
}
return $html;
}
?>
<?php echo $data['category'] = getCategories(0, $category);?>
as of your comment. i guess you need some CSS.
this will work on mouse hover. but not on click like in your example:
.mega-menu-drop {
display:none
}
.mega-menu:hover .mega-menu-drop {
display:block
}

Make a Dynamic Drop Down Navigation system

I am trying to create a Dropdown Menu on my site, Ive hit a brick wall and cannot think on how to do it.
Basically i need to check 2-3 variables in a database and out put the correct data.
I have at the moment it checking if its an External Link or Not, and if it contains a submenu, but i can't get it to output the correct information.
Basically i want it to check if its a External or Non-External link, and if it has a submenu, if it has a submenu, to display the menu options underneath it. So say i have menu 1, 2 ,3, 4 and 2,4 has a submenu, i need them to list the other links under them. i have put in my database toplink_id (to represent which link this item should be under) sc_order (which will control the order the sublinks display in) also dropdown (which tells me if the menu has a submenu or not.)
Here is the start of my code
$sql = "SELECT label, url, ext, dropdown FROM content_pages WHERE top_nav='1' AND active='1' ORDER by page_order ASC";
$query = mysqli_query($dbc, $sql) or die (mysqli_error($dbc));
$menuDisplay .= '<div class="bg-2"><div class="container_12"><article class="grid_12"><nav><ul class="menu sf-js-enabled">';
while ($row = mysqli_fetch_array($query)) {
$url = $row["url"];
$nav_label = $row["label"];
$drop_down ='<ul><li>' . $nav_label . '</li></ul>';
if ($row["ext"] == 0 && $row["dropdown"] == 1){
$menuDisplay .= '<li>' . $nav_label . '' . $drop_down . '</li>';
}
elseif ($row["ext"] == 1 && $row["dropdown"] == 1){
$menuDisplay .= '<li>' . $nav_label . '' . $drop_down . '</li>';
}
elseif ($row["ext"] == 0){
$menuDisplay .= '<li>' . $nav_label . '</li>';
}
elseif ($row["ext"] == 1)
{
$menuDisplay .= '<li>' . $nav_label . '</li>';
}
}
$menuDisplay .= '</ul></nav></article></div></div></header>';
mysqli_free_result($query);
Best way I found to do this without using jQuery is use multidimensional Arrays.
// Create a multidimensional array to conatin a list of items and parents
$menu = array(
'items' => array(),
'parents' => array(),
);
// Builds the array lists with data from the menu table
while ($items = mysqli_fetch_assoc($query))
{
// Creates entry into items array with current menu item id ie. $menu['items'][1]
$menu['items'][$items['id']] = $items;
// Creates entry into parents array. Parents array contains a list of all items with children
$menu['parents'][$items['parent']][] = $items['id'];
}
// Menu builder function, parentId 0 is the root
function buildMenu($parent, $menu)
{
$html = "\n";
if ( isset($menu['parents'][$parent]) )
{
$html .= "";
foreach ($menu['parents'][$parent] as $itemId)
{
if(!isset($menu['parents'][$itemId]) && $menu['items'][$itemId]['ext'] == 0)
{
$html .= "<li>\n <a href='../pages/".$menu['items'][$itemId]['link']."'>".$menu['items'][$itemId]['label']."</a>\n</li> \n";
}
else
if(!isset($menu['parents'][$itemId]) && $menu['items'][$itemId]['ext'] == 1)
{
$html .= "<li>\n <a href='../".$menu['items'][$itemId]['link']."'>".$menu['items'][$itemId]['label']."</a>\n</li> \n";
}
if(isset($menu['parents'][$itemId]))
{
$html .= "<li>\n <a href='../pages/".$menu['items'][$itemId]['link']."'>".$menu['items'][$itemId]['label']."<span class='arrow-down'></span></a> \n";
$html .= "<ul style='border-radius: 0px 0px 6px 6px'> \n";
$html .= buildMenu($itemId, $menu);
$html .= "</ul> \n";
$html .= "</li> \n";
}
}
$html .= "\n";
}
$html .= "";
return $html;
}

Hierarchical tree menu - PHP / MySQL

In working on a dynamic menu w/ CRUD I have been having some trouble with the finishing touches. It works, but there are some extra tags getting inserted where there shouldn't be and can't figure out how to clean it up before I share it with the world. I used this as a starting point, then changed it to work with an accordion menu (http://www.phpro.org/tutorials/Simple-Mysql-PHP-Menu.html).
Below is the data from the table (I changed the names on the first 2 fields to get it to fit in the SO format from menu_item_id to id, and from menu_parent_id to pid).
id pid menu_item_name menu_url sortorder status
1 0 Settings 0 ACTIVE
2 5 Grid Demo grid.php ACTIVE
3 5 setGridOptions gridoptions.php ACTIVE
4 1 Menu Items adminmenu.php 1 ACTIVE
5 0 Grid Settings 100 ACTIVE
6 1 General Settings settings.php 100 ACTIVE
Here is the PHP that connects to the mysql database and creates the hierarchical tree array to make it work:
include 'db.php';
$sql = "SELECT * FROM menu_items WHERE status = \"ACTIVE\" ORDER BY sortorder, menu_item_name";
$query = $db->query($sql);
while($data = $query->fetch(PDO::FETCH_ASSOC))
// loop over the results
{
// Assign by reference
$thisref = &$refs[ $data['menu_item_id'] ];
// add the the menu parent
$thisref['menu_item_id'] = $data['menu_item_id'];
$thisref['menu_parent_id'] = $data['menu_parent_id'];
$thisref['menu_item_name'] = $data['menu_item_name'];
$thisref['menu_url'] = $data['menu_url'];
// if there is no parent id
if ($data['menu_parent_id'] == 0)
{
$list[ $data['menu_item_id'] ] = &$thisref;
}
else
{
$refs[ $data['menu_parent_id'] ]['children'][ $data['menu_item_id'] ] = &$thisref;
}
}
function create_list( $arr )
{
$html = "";
foreach ($arr as $key=>$v)
{
if ($v['menu_parent_id'] == '0')
{
$html .= '<a class="menuitem submenuheader" href="'. $v['menu_url'] .'">'.$v['menu_item_name']."</a>\n";
$html .= "<div class=\"submenu\">\n<ul>\n";
$html .= "<li>" . create_list($v['children']) . "</li>";
$html .= "</ul>\n";
}
else{
$html .= '<li><a id="' . $v['menu_item_id'] . '">'.$v['menu_item_name']."</a></li>\n";
}
}
$html .= "</div>\n";
return $html;
}
echo "<div class=\"glossymenu\">";
echo create_list( $list );
echo "</div>";
When I run it, it outputs the following:
<div class="glossymenu"><a class="menuitem submenuheader">Settings</a>
<div class="submenu">
<ul>
<li><li><a id="4">Menu Items</a></li>
<li><a id="6">General Settings</a></li>
</div>
</li></ul>
<a class="menuitem submenuheader" href="">Grid Settings</a>
<div class="submenu">
<ul>
<li><li><a id="2">Grid Demo</a></li>
<li><a id="3">setGridOptions</a></li>
</div>
</li></ul>
</div>
</div>
As you can see there are extra <li> tags, the </ul> is in the wrong
spot (should be after the </div>) Other than that, it is working great.
The other thing I can't figure out is if I have a root menu item with no children, I would love it to have a different output like
<a id="8">No Children Menu Item</a>
Instead of:
<a class="menuitem submenuheader">No Children Menu Item</a>
The second example would create the make it show up the little (+/-) for expanding and contracting and wouldn't allow me to click on it. For clarification on the <a> tags, I am using javascript to do a .get() based off the id which is why there is no href or url shown.
UPDATE
It is working correctly and I posted it on Github for anyone that wants it.
https://github.com/ajhalls/php-accordian-menu
Try this :
<?php
include 'db.php';
$sql = "SELECT * FROM menu_items WHERE status = 'ACTIVE' ORDER BY pid ASC, sortorder ASC, menu_item_name ASC";
$query = $db->query($sql);
$menu_items = array();
while($data = $query->fetch(PDO::FETCH_ASSOC)) {
if($data['pid'] == 0) {
$menu_items[$data['id']] = array();
$menu_items[$data['id']]['id'] = $data['id'];
$menu_items[$data['id']]['name'] = $data['menu_item_name'];
$menu_items[$data['id']]['url'] = $data['menu_url'];
$menu_items[$data['id']]['children'] = array();
} else if($data['pid'] != 0) {
$tmp = array();
$tmp['id'] = $data['id'];
$tmp['name'] = $data['menu_item_name'];
$tmp['url'] = $data['menu_url'];
array_push($menu_items[$data['pid']]['children'],$tmp);
unset($tmp);
}
}
function create_list($arr)
{
$html = "";
foreach($arr as $key => $value) {
if(count($value['children']) > 0) {
$html .= ' <a class="menuitem submenuheader" href="'. $value['url'] .'">'.$value['name'].'</a>
<div class="submenu">
<ul>';
foreach($value['children'] AS $child) {
$html .= ' <li>
<a id="'.$child['id'].'">'.$child['name'].'</a>
</li>';
}
$html .= ' </ul>
</div>';
} else{
$html .= ' <a id="'.$value['id'].'">'.$value['name'].'</a>';
}
}
return $html;
}
echo "<div class=\"glossymenu\">";
echo create_list($menu_items);
echo "</div>";
?>

Custom pagination classes Joomla Virtuemart 2

I need to assign an custom class, lets named it "custom" to the Virtuemart Pagination "Next" link or li. Now every Li from my Ul had class "Next", but what code i should use to make Li with the link to the next page had custom class?
Here is the code
function pagination_item_active(&$item) {
$cls = '';
if ($item->text == JText::_('Next')) { $item->text = '»'; $cls = "next";}
if ($item->text == JText::_('Prev')) { $item->text = '«'; $cls = "previous";}
if ($item->text == JText::_('First')) { $cls = "first";}
if ($item->text == JText::_('Last')) { $cls = "last";}
return "<li class=\"next\"><a class=\"".$cls."\" href=\"".$item->link."\" title=\"".$item->text."\">".$item->text."</a></li>";
}
function pagination_item_inactive(&$item) {
return "<li class=\"pagination-active\"><a>".$item->text."</a></li>";
}
I have found the answer here http://forum.joomla.org/viewtopic.php?t=444384.
Here is the final solution code:
function pagination_list_render($list)
{
$lang =& JFactory::getLanguage();
$html = "<ul class=\"pagination\">";
$html .= '<li class="first">'.$list['start']['data'].'</li>';
$html .= '<li class="prev">'.$list['previous']['data'].'</li>';
foreach( $list['pages'] as $page )
{
$html .= '<li class="num">'.$page['data'].'</li>';
}
$html .= '<li class="next">'.$list['next']['data'].'</li>';
$html .= '<li class="end">'.$list['end']['data'].'</li>';
$html .= "</ul>";
return $html;
}
function pagination_item_active(&$item) {
return "".$item->text."";
}
function pagination_item_inactive(&$item) {
return "<span class=\"inactive\">".$item->text."</span>";
}
I use it to install infinite ajax scroll script, and it works perfectly.
You can set the custom class CSS using:
li.next {
}
See MDN about CSS.

How to create a nested menu from MySQL with PHP?

I need to create a menu with PHP from a MySQL database.
Table called categories has id, name, parent_id, shortdesc, etc.
The output need to have parent list and children list under the partent list as follows.
If you can show me codes or website, I will appreciate it.
<ul id="catmenu">
<li class="menulist">Cars
<ul>
<li>Ford</li>
<li>Honda</li>
<li>Toyota</li>
</ul>
</li>
<li class="menulist">Food
<ul>
<li>Pasta</li>
<li>Pizza</li>
...
</ul>
</li>
...
...
</ul>
This is specifically for two levels deep. Recommended approach should it be more is to use an optimized table structure for traversal, like http://articles.sitepoint.com/article/hierarchical-data-database/2 (pointed out elsewhere) or to pull the data you need and push it into a dictionary (associative array) and query it that way.
<?php
$query = <<<EOT
SELECT
parent.name as parent_name,
child.name as child_name,
FROM
items child
INNER JOIN
items parent
ON
child.parent_id = parent.id
ORDER BY
parent.name
EOT;
$result = mysql_query($query) or die('Failure!');
echo "<ul id=\"catmenu\">";
$last_parent = '';
while($row = mysql_fetch_array($result)){
// If this is a new category, start a new one
if($last_parent != $row['parent_name']){
// Unless this is the first item, close the last category
if($last_parent != ''){
echo "</ul></li>";
}
$last_parent = $row['parent_name'];
echo "<li class=\"menulist\">{$row['parent_name']}<ul>";
}
echo "<li>{$row['child_name']}</li>";
}
// If we actually had items, close the "category"
if($last_parent != ''){
echo "</ul></li>";
}
echo "</ul>";
?>
If you have only two levels then, you could just display them :
echo '<ul id="catmenu">';
foreach($menu as $element) {
echo '<li><ul class="menulist">';
foreach($element['submenu'] as $submenu) {
echo '<li>' . $submenu['name'] . '</li>';
}
echo '</ul></li>';
}
echo '</ul>
If you have an undefined number of submenus however you should use a Recursive Function.
function menu($item) {
$ret = '<li>' . $item['name'];
if (!empty($item['submenu'])) {
foreach($item['submenu'] as $submenu) {
$ret .= menu($submenu);
}
}
return $ret;
}
echo menu($menu);
So every of your subcategories, whatever their number is will be displayed.
You make database like this.
ID NAME PARENT
0 Cars -1
1 Foods -1
2 Ford 0
3 Honda 0
4 Toyota 0
5 Pasta 1
6 Pizza 1
...
You query them all up and put it in an array.
$Menus = array();
// In a read MySQL loop
$Menus[$i]['ID']
$Menus[$i]['NAME']
$Menus[$i]['PARENT']
// Sorry, lazy to write. I think you know what I mean.
Then you loop all menu looking for PARENT == -1. Generate all UL and IL then sub it with another nested menu.
You can simply create a function like this.
var $MenuLevelClass = array("menulist");
function CreateMenu($Menus, $Tab = 0, $Parent = -1, $Level = 0) {
global $MenuLevelClass;
$CatClass = ($Level != 0) ? '' : ' class="catmenu"';
$MenuClass = $MenuLevelClass[$Level];
if ($MenuClass != '')
$MenuClass = ' class="'.$MenuClass.'"';
$TabCount = $Level + $Tab;
$TabUL = "";
for ($t = 0; $t < $TabCount; $t++)
$TabUL = $TabUL."\t";
$TabLI = $TabUL."\t";
?>
<?=$TabUL?><ul<?=$CatClass?>>
<?php
$MenuCount = count($Menus);
for ($m = 0; $m < $MenuCount; $m++) {
$Menu = $Menu[$m];
$ID = $Menu['ID'];
if ($ID != $Parent)
continue;
?>
<?=$TabLI?><li<?=$MenuClass?>><?=$Menu['Name']?><?=CreateMenu($Menus, $Tab + 1, $ID, $Level + 1)?></li>
<?php
?>
<?=$TabUL?></ul>
<?php
}
}
And to use it just run 'CreateMenu($Menus);' or 'CreateMenu($Menus, $PrefixTabCount);'.
CreateMenu will recursively create the nested menu for you.
I have not test it so you may have to adjust it.
Hope this helps.

Categories