Database Driven Multi-Level Horizontal CSS Menu With PHP And MYSQL

Database Driven Multi-Level Horizontal CSS Menu With PHP And MYSQL

There is no doubt in the truth that A website should have a good and proper navigation from user point of view to attract more visitors. Creating css navigation using php and mysql is always a headache for php newbies. In this article I’ve told that how to manage a horizontal css navigation menu from a single mysql table and a small piece of PHP code. Instead of wasting your time I come to our main tutorial. Go through the following points and make your own navigation menu.

Database Driven Multi-Level Horizontal CSS Menu With PHP And MYSQL

Database Driven Multi-Level Horizontal CSS Menu With PHP And MYSQL

1. Database Table “menus”:

First of all make your database table to manage the menus as shown below.

Database Driven Multi-Level Horizontal CSS Menu With PHP And MYSQL

As you are seeing, the table has only four fields. First column is id of each menu that is primary key and last column is the id of parent of each menu. You’ll understand yourself by seeing the structure. Although I’ve given the demo sql database dump in zip file.

2.  Style Sheet Or Markup (style.css) :

Just apply the following css to your navigation menu.

#cssmenu ul,
#cssmenu li,
#cssmenu span,
#cssmenu a {
  margin: 0;
  padding: 0;
  position: relative;
}
#cssmenu {
  height: 49px;
  border-radius: 5px 5px 0 0;
  -moz-border-radius: 5px 5px 0 0;
  -webkit-border-radius: 5px 5px 0 0;
  background: #141414;
  background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAxCAIAAACUDVRzAAAAA3NCSVQICAjb4U/gAAAALElEQVQImWMwMrJi+v//PxMDw3+m//8ZoPR/qBgDEhuXGLoeYswhXg8R5gAAdVpfoJ3dB5oAAAAASUVORK5CYII=) 100% 100%;
  background: -moz-linear-gradient(top, #32323a 0%, #141414 100%);
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #32323a), color-stop(100%, #141414));
  background: -webkit-linear-gradient(top, #32323a 0%, #141414 100%);
  background: -o-linear-gradient(top, #32323a 0%, #141414 100%);
  background: -ms-linear-gradient(top, #32323a 0%, #141414 100%);
  background: linear-gradient(to bottom, #32323a 0%, #141414 100%);
  border-bottom: 2px solid #e00f16;
}
#cssmenu:after,
#cssmenu ul:after {
  content: '';
  display: block;
  clear: both;
}
#cssmenu a {
  background: #141414;
  background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAxCAIAAACUDVRzAAAAA3NCSVQICAjb4U/gAAAALElEQVQImWMwMrJi+v//PxMDw3+m//8ZoPR/qBgDEhuXGLoeYswhXg8R5gAAdVpfoJ3dB5oAAAAASUVORK5CYII=) 100% 100%;
  background: -moz-linear-gradient(top, #32323a 0%, #141414 100%);
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #32323a), color-stop(100%, #141414));
  background: -webkit-linear-gradient(top, #32323a 0%, #141414 100%);
  background: -o-linear-gradient(top, #32323a 0%, #141414 100%);
  background: -ms-linear-gradient(top, #32323a 0%, #141414 100%);
  background: linear-gradient(to bottom, #32323a 0%, #141414 100%);
  color: #ffffff;
  display: inline-block;
  font-family: Helvetica, Arial, Verdana, sans-serif;
  font-size: 12px;
  line-height: 49px;
  padding: 0 20px;
  text-decoration: none;
}
#cssmenu ul {
  list-style: none;
}
#cssmenu > ul {
  float: left;
}
#cssmenu > ul > li {
  float: left;
}
#cssmenu > ul > li:hover:after {
  content: '';
  display: block;
  width: 0;
  height: 0;
  position: absolute;
  left: 50%;
  bottom: 0;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-bottom: 10px solid #e00f16;
  margin-left: -10px;
}
#cssmenu > ul > li:first-child > a {
  border-radius: 5px 0 0 0;
  -moz-border-radius: 5px 0 0 0;
  -webkit-border-radius: 5px 0 0 0;
}
#cssmenu > ul > li:last-child > a {
  border-radius: 0 5px 0 0;
  -moz-border-radius: 0 5px 0 0;
  -webkit-border-radius: 0 5px 0 0;
}
#cssmenu > ul > li.active > a {
  box-shadow: inset 0 0 3px #000000;
  -moz-box-shadow: inset 0 0 3px #000000;
  -webkit-box-shadow: inset 0 0 3px #000000;
  background: #070707;
  background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAxCAIAAACUDVRzAAAAA3NCSVQICAjb4U/gAAAALklEQVQImWNQU9Nh+v//PxMDw3+m//8ZkNj/mRgYIHxy5f//Z0BSi18e2TwS5QG4MGB54HL+mAAAAABJRU5ErkJggg==) 100% 100%;
  background: -moz-linear-gradient(top, #26262c 0%, #070707 100%);
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #26262c), color-stop(100%, #070707));
  background: -webkit-linear-gradient(top, #26262c 0%, #070707 100%);
  background: -o-linear-gradient(top, #26262c 0%, #070707 100%);
  background: -ms-linear-gradient(top, #26262c 0%, #070707 100%);
  background: linear-gradient(to bottom, #26262c 0%, #070707 100%);
}
#cssmenu > ul > li:hover > a {
  background: #070707;
  background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAxCAIAAACUDVRzAAAAA3NCSVQICAjb4U/gAAAALklEQVQImWNQU9Nh+v//PxMDw3+m//8ZkNj/mRgYIHxy5f//Z0BSi18e2TwS5QG4MGB54HL+mAAAAABJRU5ErkJggg==) 100% 100%;
  background: -moz-linear-gradient(top, #26262c 0%, #070707 100%);
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #26262c), color-stop(100%, #070707));
  background: -webkit-linear-gradient(top, #26262c 0%, #070707 100%);
  background: -o-linear-gradient(top, #26262c 0%, #070707 100%);
  background: -ms-linear-gradient(top, #26262c 0%, #070707 100%);
  background: linear-gradient(to bottom, #26262c 0%, #070707 100%);
  box-shadow: inset 0 0 3px #000000;
  -moz-box-shadow: inset 0 0 3px #000000;
  -webkit-box-shadow: inset 0 0 3px #000000;
}
#cssmenu .has-sub {
  z-index: 1;
}
#cssmenu .has-sub:hover > ul {
  display: block;
}
#cssmenu .has-sub ul {
  display: none;
  position: absolute;
  width: 200px;
  top: 100%;
  left: 0;
}
#cssmenu .has-sub ul li {
  *margin-bottom: -1px;
}
#cssmenu .has-sub ul li a {
  background: #e00f16;
  border-bottom: 1px dotted #ec6f73;
  filter: none;
  font-size: 11px;
  display: block;
  line-height: 120%;
  padding: 10px;
}
#cssmenu .has-sub ul li:hover a {
  background: #b00c11;
}
#cssmenu .has-sub .has-sub:hover > ul {
  display: block;
}
#cssmenu .has-sub .has-sub ul {
  display: none;
  position: absolute;
  left: 100%;
  top: 0;
}
#cssmenu .has-sub .has-sub ul li a {
  background: #b00c11;
  border-bottom: 1px dotted #d06d70;
}
#cssmenu .has-sub .has-sub ul li a:hover {
  background: #80090d;
}

3. PHP Script (index.php):

This is the main PHP file that will fetch the menus from database and show them in your navigation menu using while loop. The script is written for 3 Level CSS menu. You can extend it for nth level by running the loop n times as it is.

<?php
//database connection
$dbname = 'csc';
$link = mysql_connect("localhost","root","") or die("Couldn't make connection.");
$db = mysql_select_db($dbname, $link) or die("Couldn't select database");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Database Driven Multi-Level Horizontal CSS Menu With PHP And MYSQL</title>
<link type="text/css" rel="stylesheet" href="styles.css" />
</head>
<body>
	<h2>Database Driven Multi-Level Horizontal CSS Menu With PHP And MYSQL</h2>
<div style="width:728px;margin:auto;">
	<div id='cssmenu'>
		<ul>
<?php
function query($parent_id) { //function to run a query
	$query = mysql_query ( "SELECT * FROM menus WHERE parent_id=$parent_id" );
	return $query;
}
function has_child($query) { //This function checks if the menus has childs or not
	$rows = mysql_num_rows ( $query );
	if ($rows > 0) {
		return true;
	} else {
		return false;
	}
}
function fetch_menu($query) {
	while ( $result = mysql_fetch_array ( $query ) ) {
		$menu_id = $result ['id'];
		$menu_name = $result ['menu_name'];
		$menu_link = $result ['menu_link'];
		echo "<li  class='has-sub '><a href='{$menu_link}'><span>{$menu_name}</span></a>";
		if (has_child ( query ( $menu_id ) )) {
			echo "<ul>";
			fetch_menu ( query ( $menu_id ) );
			echo "</ul>";
		}
		echo "</li>";
	}
}
fetch_menu (query(0)); //call this function with 0 parent id
?>
		</ul>
	</div>
	</div>
</body>
</html>

The tutorial is only for making you understand that what is happening. Otherwise you can download the zip file given above and implement it in your website. Just by changing the database connection properties and change your menu names and their links in database table. I hope you enjoyed the tutorial. Waiting for your comments.

Note: The same code can be used for both horizontal and vertical css menus.

18 Responses to “Database Driven Multi-Level Horizontal CSS Menu With PHP And MYSQL”
  1. CoursesWeb says:

    Hi,
    Looking for “Multiple level menu” i found this article.
    Here is a good script to create multi-level menus, maybe you find it useful:
    http://coursesweb.net/javascript/multi-level-menu-creator_s2
    The script is made with Ajax, and provides an user interface for composing HTML menus code; to Add, Modify, and Delete lists and links in menu.
    Than, generates the HTML and CSS code for menu to can be copied and included in web pages.

  2. ranbir kumar das says:

    HOW TO BREAK Drop down menu TO PERTICULAR LEVEL

  3. Daniel Chikaka says:

    thanks, it was very helpful

  4. jaime romo says:

    hello there im traying to use your menu but im recibing this error

    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in F:\xampp\htdocs\tuedificiowebdemo.com\scripts\php\index.php on line 39

    any help please

    • please ensure that you have properly imported the database given in zip file and don’t edit the name of database fields.

      • sudhir bansal says:

        First of all Thanks a lot to solve my big problem ,now my second query is how to create parent _id automatically pls send reply soon
        Thanks a lot
        9876128007

  5. Brian says:

    I’m wondering how to open a link in a new window with this. I created a column in the db named menu_target and tried a href=’{$menu_link}’ rel=”nofollow” but that didn’t work. Any thoughts? This menu is awesome but I need to open external links too. Thanks in advance!

  6. SlikkaticZ says:

    Awesome tutorial sir!

    I managed to get it working, however it does not work to keep the menu item active, so there is no way of telling which page your on.

    It would be great if you could explain us how to make it show active menu items, for example if i click on: Bikes -> TVS -> TVS star city it should highlight Bikes – TVS and TVS star city.

    Please help man

    • You mean you want the active menu keep opened??????

      • SlikkaticZ says:

        No, i want the parent of the child being active (highlighted). Now it stays the same color as everything else. On most menu’s you can see which page your on as the clicked item becomes a different color, and this also applies to the childs/parents of the item you click.

        For example when i click in the menu on: Bikes -> TVS -> TVS star city it should highlight Bikes – TVS and TVS star city and leave the rest default color.

        Thank you very much!

        • If I understand the question correctly I would suggets to use the breadcrumb technique. Actually including the complete path in the database can make it easier to maintain complex menus. You could use that dat as breadcrumb trail.

  7. SlikkaticZ says:

    Never mind sir, i managed to get it to work myself by some javascript. Give your ul a id name: #MenuBar1 and post the code below on the same page, and it will auto select the parent/childs of the items. Been looking for days for this!

    $(document).ready(function()
    {

    var url = window.location.pathname;
    var page = url.substr(url.lastIndexOf(‘/’) + 1);

    if (page)
    {
    $(‘#MenuBar1 li a[href="' + page + '"]‘).addClass(‘active’);
    $(‘.active’).parents().children(‘li a’).addClass(‘active’);

    }

    });

  8. danish says:

    Hi. how to add/edit new categories using this code? I tried but could not get it

Leave a Reply

Manish Jangir - Find me on Bloggers.com