Categories
PHP

How To Create Dynamic Drop Down Menu In PHP

How To Create Dynamic Drop Down Menu In PHP

In this tutorial i will teach you How To Create Dynamic Drop Down Menu In PHP.We are using MySQL as back-end.

CSS:

.bdy
{
margin: 0px auto;
width:800px;
font-family:Calibri;
font-size:14px;
padding-top:100px;
}

ul {
font-family:Calibri;
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 5px 15px;
    background: #000;
    margin-left: 1px;
    white-space: nowrap;
}
ul li a:hover {
background: #ccc;
color:#000;
}
li:hover ul {
    display: block;
    position: absolute;
}
li:hover li {
    float: none;
    font-size: 13px;
}
li:hover a { background: #3b3b3b; }
li:hover li a:hover {
    background: #1e7c9a;
}

Create Tables:

CREATE TABLE menu (
menu_id int(11) NOT NULL AUTO_INCREMENT,
menu_name varchar(50) NOT NULL,
PRIMARY KEY (`menu_id`)
)

--Sub Menu Table--

CREATE TABLE sub_menu (
  sub_menu_id int(11) NOT NULL AUTO_INCREMENT,
  sub_menu varchar(50) NOT NULL,
  menu_id int(11) NOT NULL,
  link varchar(40) NOT NULL,
  PRIMARY KEY (`sub_menu_id`)
)

Config File:

<?php
$hostname_conn = "localhost";
$database_conn = "mycreation";
$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".mysql_error());
?>

Index.PHP:

<?php
 // Included configuration file in our code.
include("config.php");
?>
<html>
<head>
<title>Dynamic Drop Down menu in php</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body class="bdy">
<table>
<tr>
<td>
<ul id="Drop_Down_Menu">
<?php
// Creating query to fetch state information from mysql database table.
$state_query = "select * from menu";
$state_result = mysql_query($state_query);
while($r = mysql_fetch_array($state_result)){ ?>
 <li><a href="#"><?php echo $r['menu_name'];?></a>
 <ul>
 <?php
 $city_query = "select * from sub_menu where menu_id=".$r['menu_id'];
 $city_result = mysql_query($city_query);
 while($r1 = mysql_fetch_array($city_result)){ ?>
  <li><a href="<?php echo $r1['link'];?>"><?php echo $r1['sub_menu'];?></a></li>
 <?php } ?>
 </ul>
 </li>
<?php } ?>
</ul>
</td>
</tr>
</table>
</body>
</html>

Enjoy 🙂

3 replies on “How To Create Dynamic Drop Down Menu In PHP”

I must admit that your post is really interesting. I have spent a lot of my spare time reading your content. Thank you a lot!

Comments are closed.