PHPSuperBlog.com

HTML form – Drop down menu with data from MySQL datebase as options

To create a drop down menu is easy, just use the codes I mentioned in my past post: HTML form element – Drop down menu.

But what if you want to have the data in the MySQL database to be the options of the drop down menu and the options are over 100 or more?? It is very time consuming to create all. But I am going to show you an easy way to do so which by creating a drop down menu involving with PHP and query. The codes are:

First we have to connect to database.

<?php
mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");
?>

Here then we have to create and run a query to select all from a field of a table where the options are located:

<?php
$query = "SELECT * FROM table";
$result = mysql_query($query);
?>

We have closed the PHP tag here because the drop down menu is HTML form element but not a PHP element. Here back to HTML codes and we create the drop down menu.

<select name="select1">

Here we are back to PHP again, and we will go through the MySQL table field which we selected with the query and we now will go through record by record to see if it meet the criteria of the query, the query is “select * from table” which means select all from table, therefore in this case, we will use every record of the field as option.

<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>

Here, we close the PHP tag again and back to HTML, because we now have selected the option for the drop down menu: option consists of 2 parts, one is value and one is the text shows to the user, because the value and the text are both the record from the MySQL, therefore to put PHP variables in HTML, we have to echo it out. In the below example, replace the “field” with the field name of the field which you want the option from the MySQL database

<option value="<?php echo $line[field];?>"> <?php echo $line[field];?> </option>

end this loop:

<?php
}
?>

Close the drop down menu

</select>

All together we have:

<?php
mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");
$query = "SELECT * FROM table";
$result = mysql_query($query);
?>
<select name="select1">
<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line[field];?>"> <?php echo $line[field];?> </option>
<?php
}
?>
</select>
VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Similar Posts:

Leave a comment