How to Do Multilevel Menu the Correct Way With MySQL PHP

How to do Multilevel menu the correct way with MySQL PHP?

You're going to want to loop through the results of the query and print something like this. I've used dashes to indent, but you can use html to do that more cleanly. I've made a db fiddle for anyone else who wants to help. https://www.db-fiddle.com/f/sbTyQbNemcEM5vX3xwuUaJ/0#&togetherjs=wkJd3lwafs

<?php 
$cat = $getData->get_menu_categories();
$lastmain = '';
$lastsub = '';
$lastsubsub = '';

foreach ($cat as $line) {
$main = $line['main_menu_name'];
$sub = $line['sub_menu_name'];
$subsub = $line['sub_sub_menu_name'];

if ($lastmain <> $main) {
print "$main\n";
$lastmain = $main;
}

if ($lastsub <> $sub) {
print "---$sub\n";
$lastsub = $sub;
}

if ($lastsubsub <> $subsub) {
print "------$subsub\n";
$lastsubsub = $subsub;
}
}

How to make multilevel menu in php, mysql?

I think the code should be change like this.

if(mysqli_num_rows($run_query2)>0){`
$j++;
echo "HTML code 'attribute' ".$cat_name."HTML code";`
} else {`
echo "HTML code".$cat_name."HTML code";`
}

display multilevel database driven menu in php

Here is a recursive solution.

The code is fully commented.

There are two useful checks in the processMenuEntry routine that can conveniently be done so that you can decide if you want different actions to happen.

  • Check whether the 'current' 'entry' is the 'root' node.

    $isRoot = $currentEntry['cat_id'] == 0; // do 'First time' processing

  • Check whether the current 'entry' has a 'submenu'.

    if (!empty($subMenu)) { ...

Q29910284-display-multilevel-database-driven-menu.php

The code:

Database connection:

$DB_HOST     = "localhost";
$DB_USER = "test";
$DB_PASSWORD = "test";
$DB_TO_USE = "testmysql";

$dbc = new mysqli($DB_HOST, $DB_USER, $DB_PASSWORD, $DB_TO_USE);

Submenu Query:

/** -----------------------------------------------------------------
* Select all the menu entries for a given entry Id
*
* Note: it is safe to do 'parameter substitution' rather than using
* 'prepared queries' with placeholders as this 'entry Id' never
* comes from an external source.
*
* @param mysqli $dbc
* @param integer $currentEntryId
* @return array of menu entries
*/
function selectSubMenu($currentEntryId, $dbc)
{
$sql = "SELECT cat_id, cat_name, cat_parent_id
FROM catalogue
WHERE cat_parent_id = {$currentEntryId}
ORDER BY cat_id";
$resultSet = mysqli_query($dbc, $sql);
return $resultSet->fetch_all(MYSQLI_ASSOC);
}

Process Current Menu Entry:

/** --------------------------------------------------------------------------
* Process the current menu enty - it will return a complete menu as HTML
*
* These needs to know whether the current entry has a submenu and
* will therefore need to generate an 'unordered list' for the current entry.
*
* Alas, it also has to not display the 'list item text' for the 'root' entry
* but process the 'submenu'.
* This complicates the <li> current entry text generation slightly.
*
* @param array $currentEntry - one row
* @param array $subMenu - many rows - may be empty
* @param mysqli $dbc - database connection
* @return string - the HTML for the menu
*/
function processMenuEntry($currentEntry, array $subMenu, $dbc) {
$outMenu = '';
$isRoot = $currentEntry['cat_id'] == 0; // do 'First time' processing

// display the current entry text as a 'list item'
$outMenu .= !$isRoot ? "<li><a href='#'>" . $currentEntry['cat_name'] . "</a>" : '';

// does it have a submenu...
if (!empty($subMenu)) { // we need to add a complete submenu of <ul> ... </ul>

// Start of the submenu as an unordered list -- decide what is required
if ($isRoot) {
$outMenu .= '<ul class="dropdown">';
}
else {
$outMenu .= '<ul>';
}

// Display each entry of the submenu as a 'list item'
foreach ($subMenu as $submenuEntry) {
$outMenu .= processMenuEntry($submenuEntry,
selectSubMenu($submenuEntry['cat_id'], $dbc),
$dbc);
}

// close the current submenu - terminate the unordered list
$outMenu .= '</ul>';
}

// terminate the current list item
$outMenu .= !$isRoot ? '</li>' : '';
return $outMenu;
};

Process all the menu entries:

/* -------------------------------------------------------------------
* Process all the menu entries
*
* We need a complete menu 'tree' that includes a 'root' which is not provided
* in the database. I think it should be. Whatever, i need one.
*
* Initializing a 'tree walk' i always find 'interesting' ;-/
*/
$root = array('cat_id' => 0, 'cat_name' => '', 'cat_parent_id' => 0);

// build the output menu
$outMenu = processMenuEntry($root,
selectSubMenu($root['cat_id'], $dbc),
$dbc);

// wrap it in a <div>
$htmlMenu = '<div style="border: 1px solid red">'
. $outMenu
.'</div>';
?>

Output the generated HTML:

<!DOCTYPE html>
<html>
<head>
<title>Test Recursive Menu Builder</title>
</head>
<body>
<?= $htmlMenu ?>
</body>
</html>

The generated HTML

<!DOCTYPE html>
<html>
<head>
<title>Test Recursive Menu Builder
</title>
</head>
<body>
<div style="border: 1px solid red">
<ul class="dropdown">
<li>
<a href='#'>Home</a>
</li>
<li>
<a href='#'>About</a>
<ul>
<li>
<a href='#'>History</a>
</li>
<li>
<a href='#'>Services</a>
</li>
</ul>
</li>
<li>
<a href='#'>Contact</a>
</li>
</ul>
</div>
</body>
</html>

Dynamic multi level Menu and submenu php mysql

As your menu and sub-menu are in different table you can select menu first and then select sub-menu depending on the menu selected .i.e :

 <?php
//getting menu first
$sql = 'SELECT id,intitule FROM rubriques';
$stmt = $conn->query($sql);
if ($stmt->num_rows > 0) {
while($row = $stmt->fetch_assoc()){
//getting values
$intitule = $row['intitule '];
$idr = $row['id']; ?>
<!--your menu-->
<li class="active"><a href="index.html"><?php
echo $intitule;
?></a>
<?php
//passing the id from first to action table for compare and retrieve that rows only
$sql1 = 'SELECT * FROM actions where idr= ' . $idr;
$stmt1 = $conn->query($sql1);
?>
<ul class="dropdown">
<?php
while ($row1 = $stmt->fetch_assoc()) {
$lien = $row1['lien'];
$intitulee = $row1['intitulee'];
?>

<!--your submenu-->
<li><a href="<?php echo $lien;?>"><?php echo $intitulee; ?></a></li>

<?php

}
?>
</ul> <!--closing ul -->

</li>
<?php
}//closing while
} //closing if
?>

How to create a mysql php multi-level list navigation

Here is code I used. It builds unordered list with unlimited level of subitems.

/*
* Table has 3 fields: `ID`, `PARENTID` and `NAME`
* `ID` is unique, `PARENTID` showing his parent node id.
* This function will go through it and build unordered list and call itself when needed to build subitems.
* $level argument used to define wich node's subitems to build. Default is 0 which is top level.
*/

function showMenu($level = 0) {

$result = mysql_query("SELECT * FROM `tbl_structure` WHERE `PARENTID` = ".$level);
echo "<ul>";
while ($node = mysql_fetch_array($result)) {
echo "<li>".$node['NAME'];
$hasChild = mysql_fetch_array(mysql_query("SELECT * FROM `tbl_structure` WHERE `PARENTID` = ".$node['ID'])) != null;
IF ($hasChild) {
showMenu($node['ID']);
}
echo "</li>";
}
echo "</ul>";
}

Hope that helps.

Responsive Vertical multilevel menu with PHP and MYSQL

Try Below, this will work for your senario.

CSS for tree view

   ul.tree, ul.tree ul {
list-style: none;
margin: 0;
padding: 0;
}
ul.tree ul {
margin-left: 10px;
}
ul.tree li {
margin: 0;
padding: 0 7px;
line-height: 20px;
color: #369;
font-weight: bold;
border-left:1px solid rgb(100,100,100);

}
ul.tree li:last-child {
border-left:none;
}
ul.tree li:before {
position:relative;
top:-0.3em;
height:1em;
width:12px;
color:white;
border-bottom:1px solid rgb(100,100,100);
content:"";
display:inline-block;
left:-7px;
}
ul.tree li:last-child:before {
border-left:1px solid rgb(100,100,100);
}

PHP structure for Ul li

 <div id="cssmenu">
<?php
$menu = '';
$file="Images/store.png";
$menu .= "<ul class='tree'>";
$sql = mysqli_q

uery($db, "SELECT * From category");
$row = mysqli_num_rows($sql);
if($row>0){
while ($row = mysqli_fetch_array($sql)){

$menu .= "<li><a href='".$row['CatId']."' style=width:174px\;>".$row['CatName']."</a>";
$menu .= "<ul>";
$sql1 = mysqli_query($db, "SELECT * FROM subcategory WHERE CatId='".$row['CatId']."'");
$row1 = mysqli_num_rows($sql1);
if($row1>0){
while ($row1 = mysqli_fetch_array($sql1)){

$menu .= "<li><a href='".$row1['SubCatId']."' style=width:174px\;color:#40404C\;font-size:13px\;font-family:openSans\;>".$row1['SubCatName']."</a>";
$menu .= "<ul>";
$sql2 = mysqli_query($db, "SELECT * FROM specificcategory WHERE SubCatId='".$row['SubCatId']."'");
$row2 = mysqli_num_rows($sql2);
if($row2>0){
while ($row2 = mysqli_fetch_array($sql2)){

$menu .= "<li><a href='".$row2['SpecCatId']."' style=width:174px\;color:#40404C\;font-size:13px\;font-family:openSans\;>".$row1['SpecCatName']."</a></li>";
}
}
$menu .= "</ul>";
$menu .="</li>";
}
}
$menu .= "</ul>";
$menu .="</li>";
}
}
$menu .= "</ul>";

echo $menu;
?>
</div>

Multilevel menu from database records

The code for this would be something like the following (This will need to be changed for whatever way you interact with the database etc.):

// Here we do a query to get all the rows from the table
$db_result = db_execute_query('SELECT * FROM `menu_table` ORDER BY `order_no`');

// Here we take the rows and put it into a structured array
$items = array();
$hierarchy = array('' => array());
while ($row = db_fetch_row($db_result)) {
$items[$row['menu_name']] = $row['menu_name_en'];
if ($row['main_menu'] == 'yes') {
$hierarchy[''][] = $row['menu_name'];
} else {
if (!isset($hierarchy[$row['sub_menu']]) {
$hierarchy[$row['sub_menu']] = array();
}
$hierarchy[$row['sub_menu']][] = $row['menu_name'];
}
}

// Here we define a recursive function to run through our $hierarchy array;
function show_menu($name = '') {
if (isset($hierarchy[$name])) {
if ($name == '') {
echo '<ul class="dropdown">';
} else {
echo '<ul class="sub_menu">';
}

foreach ($hierarchy[$name] as $sub) {
echo '<li><a href="#">' . $items[$sub] . '</a>';
show_menu($sub);
echo '</li>';
}

echo '</ul>';
}
}

// Here we execute the recursive function on the main menu
show_menu('');

Try to understand what I'm doing here instead of just implementing it verbatim. Once you get to know recursive functions, a whole new world can open for you.

Also note that your db table could be changed to make this code simpler

Multilevel menu in mysql/php

If you want to load everything with one query, what makes sense because most likely you will not have thousands of items in the menu, then you can simplify your task and do more with PHP instead of overcomplicating the SQL query.

So first you just load everything with the simplest possible query:

$items = query('SELECT * FROM `menu_items` WHERE categories_id = ? ORDER BY `ord` asc');

In that way the order will be preserved after dividing all items into submenus. Then you just need one loop to build menu structure.

$itemsById = [];
$children = [];
foreach ($items as $item) {
$itemsById[$item['id']] = $item;
$children[$item['parent']][] = $item['id'];
}

And you can print it recursively starting from $children[0].



Related Topics



Leave a reply



Submit