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 ...

Get Web Site Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.