Manchester Web Design Web Design & SEO Manchester Web Design Portfolio Get a Free Quote

We are an affordable and professional
Web Design & SEO company in Manchester.

Dynamic Form Drop Down (Option – Select) menu in PHP + MySQL

Makes use of:

  • PHP
  • MySQL
  • HTML

Use PHP to create dynamic drop down menus from data stored in a MySQL database

PHP is great fun to work with, it’s even more fun when you can use it to do things dynamically. To have PHP render things in milliseconds that would have taken minutes to do manually.

PHP & MySQL work really well together in creating dynamic website code which keeps your content fresh, and ever changing. See how you can adapt this code to have PHP dynamically output different content, form elements and lists from your MySQL database.

The simple pair of functions below, will connect to a MySQL Database, and build a XHTML compatible, dynamic drop down menu in HTML ready for output to the browser. You can use this with any data, simply change the query to suit your needs.

<?php
function database_connect($select_database)
{
    $resource_link = mysql_connect("localhost", "root", "");
    if (mysql_select_db($select_database, $resource_link)) {
        return $resource_link;
    } else {
        echo "Cannot connect to DB";
        return false;
    }
}

function print_dropdown($query, $link){
    $queried = mysql_query($query, $link);
    $menu = '<select name="staff_name">';
    while ($result = mysql_fetch_array($queried)) {
        $menu .= '
      <option value="' . $result['id'] . '">' . $result['name'] . '</option>';
    }
    $menu .= '</select>';
    return $menu;
}

//Some other form elements, or just start a form.
echo '<form method="post" action="">';

//The important bit
echo print_dropdown("SELECT id, name FROM staff LIMIT 0, 30", database_connect("general"));

//Some other form elements, or just end the form.
echo '<input type="submit" name="submit" value="submit"/>
    </form>';

Simply copy and paste the code above, and adjust the MySQL query to suit your table and data. You’ll then be able to keep your pages and content dynamic, with changes to the data in the MySQL database being reflected instantly in your website.

This entry was posted in Web Development and tagged , , , , , . Bookmark the permalink.

Comments are closed.

A Rija Group site

Switch to our mobile site