How to Link a Text Database to a Drop-Down Menu
Linking your website's drop-down menu to a database is helpful when you don't want to hard code the different menu options into an HTML file. For example, your drop-down menu options might be time-sensitive and need to change dynamically according to an algorithm running in the background. One way to create dynamic values is by having your website connect to a MySQL database with PHP code and populating the menu with data from a database query.
Instructions
-
-
1
Open the HTML file containing the code for your drop-down menu in an editor, such as Windows Notepad.
-
2
Locate the lines of code specifying the values for the drop-down menu, which will be similar to the following code:
<li><a href="page1.html">Menu 1</a>
<ul>
<li><a href="option.html?id=1">Option 1</a>
<li><a href="option.html?id=2">Option 2</a>
<li><a href="option.html?id=3">Option 3</a>
</ul>
</li> -
-
3
Delete all the lines containing the drop-down menu values. For the previous example, remove all the lines starting with "<li>" in between the "<ul>" tags. The remaining code is:
<li><a href="page1.html">Menu 1</a>
<ul>
</ul>
</li> -
4
Connect to your MySQL database by adding the following PHP code right before the drop-down menu code:
<?php
mysql_connect("localhost," "username," "password") or die(mysql_error());
mysql_select_db("nameofdatabase") or die(mysql_error());Replace "localhost," "username," "password" and "nameofdatabase" with the login information for your database.
-
5
Query the database for values with which to populate the drop-down menu by adding the following code after the database connection code:
$result = mysql_query("SELECT name, id FROM mytable");
?>The PHP "$result" variable will contain a series of names and IDs from the MySQL database.
-
6
Populate the drop-down menu with the data from the database query by adding the following PHP code where the drop-down menu values were previously:
<li><a href="page1.html">Menu 1</a>
<ul><?php
while ($row = mysql_fetch_assoc($result)) {
echo '<li><a href="option.html?' .$row['id']. '">' .$row['name']. '</a>';
}
?></ul>
</li> -
7
Save the HTML file and load it on your server to view the new drop-down menu.
-
1