Static vs Dynamic Menu
A static menu has its items hard-coded in HTML — you must edit the code every time you want to add or remove a menu item. A dynamic menu fetches its items from a database, so adding a new entry to the database automatically appears in the front-end menu.
This tutorial builds a dynamic horizontal drop-down menu from two MySQL tables: state (top-level menu) and city (sub-menu items per state).
Database Structure
Create a database named myhotel with these two tables:
-- state table
state_id | state_name
---------|------------
1 | Maharashtra
2 | Gujarat
4 | Karnataka
-- city table
city_id | state_id | city_name
--------|----------|------------
1 | 1 | Mumbai
2 | 1 | Pune
3 | 1 | Thane
4 | 2 | Gandhi Nagar
Step 1 — Create config.php
<?php
$hostname_conn = "localhost";
$database_conn = "myhotel";
$username_conn = "root";
$password_conn = "";
$conn = mysql_connect($hostname_conn, $username_conn, $password_conn)
or trigger_error(mysql_error(), E_USER_ERROR);
mysql_select_db($database_conn, $conn)
or die("Could not select database: " . mysql_error());
?>
Step 2 — Create the Menu PHP File
<?php include("config.php"); ?>
<html>
<head>
<title>Dynamic Drop Down Menu in PHP</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<ul id="Drop_Down_Menu">
<?php
$state_query = "SELECT * FROM state";
$state_result = mysql_query($state_query);
while ($r = mysql_fetch_array($state_result)) { ?>
<li>
<a href="#"><?php echo $r['state_name']; ?></a>
<ul>
<?php
$city_query = "SELECT * FROM city WHERE state_id=" . $r['state_id'];
$city_result = mysql_query($city_query);
while ($r1 = mysql_fetch_array($city_result)) { ?>
<li><a href="#"><?php echo $r1['city_name']; ?></a></li>
<?php } ?>
</ul>
</li>
<?php } ?>
</ul>
</body>
</html>
Step 3 — CSS for the Menu (style.css)
ul {
font-family: Arial, Verdana;
font-size: 14px;
margin: 0;
padding: 0;
list-style: none;
}
ul li {
display: block;
position: relative;
float: left;
}
li ul {
display: none;
}
ul li a {
display: block;
text-decoration: none;
color: #ffffff;
border-top: 1px solid #ffffff;
padding: 5px 15px;
background: #1e7c9a;
margin-left: 1px;
white-space: nowrap;
}
ul li a:hover {
background: #3b3b3b;
}
li:hover ul {
display: block;
position: absolute;
}
li:hover li {
float: none;
font-size: 11px;
}
li:hover a {
background: #3b3b3b;
}
li:hover li a:hover {
background: #1e7c9a;
}
Hope this tutorial is useful for you. Keep following PHP Tutorial for Beginners for more help.