O'Reilly logo

Web Site Cookbook by Doug Addison

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

7.5. Generating Form Menu Choices from a Database

Problem

You want to create dynamic form menus from values stored in a database.

Solution

Create a PHP function that compiles all the values in a database table into a select menu that can be placed in a form. Then call the function as needed in various places on your web site:

	<? echo makeSelectList(dbTable, dbFieldValue, dbFieldDisplay, menuField); ?>

Discussion

The ability to grow painlessly is one of the most important qualities of a successful web site. If you have one or more forms on your site that require visitors to make choices from a large and ever-changing menu of options, then you may be able to save a lot of time by storing the menu choices in a database and using a PHP function to generate forms menus from records in that database.

Tip

This Recipe makes a couple of assumptions. Since it uses PHP scripting to manipulate the text, you'll need some familiarity with the use of variables and functions in that language. Also, you'll need to have access to an SQL database and some familiarity with creating queries for it.

For the function to work properly, you'll need to have an active connection to your web database. A basic connection to a MySQL database with PHP looks like this:

	$dbName = "mydatabase";

	$dbConnection = mysql_connect("dbhost","dbuser", "dbpassword")
	  or die("Couldn't Connect.");

	$db = mysql_select_db($dbName, $dbConnection)
	  or die("Couldn't select database.");

Tip

I recommend saving these three lines in an include file ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required