PHP dynamic drop down menu or horizontal menu:
In  this tutorial of php code for beginners we will show how to create Dynamic drop down menu bar or Dynamic drop down horizontal menu in php with use of mysql database.

Create a database named myhotel and two table in it called state and city.
The state table contain the state name and state id fields  The city table contain city name, city id and state id in which he belong.

State table look like:-
state_id  state_name
Maharashtra
Gujarat
Karnataka

City table look like:-
 city_id  state_id             state_name
Mumbai
Pune
Thane
Gandhi nagar

Step 1:- Create a php configuration file which store the mysql database information. In my case it is 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".mysql_error());
?>

Step 2:- Now create php file which contain your Dynamic menu.

 <?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>
<ul id="Drop_Down_Menu">
<?php
// Creating query to fetch state information from mysql database table.
$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 you Menu bar. Put this in to style.css file.

<style type="text/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 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;
}

</style>

Now your Dynamic drop down menu bar or horizontal menu is ready to use.

0 comments:

Post a Comment

Subscribe to RSS Feed Follow me on Twitter!