Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

application. Other times the contents are generated, such as choosing month, day, and
year. There are two aspects to this problem. First, there is the fairly simple problem of
creating all the values for the OPTION tags. This is best accomplished in a loop. The
second issue deals with preselecting one of the options.


Regardless of the source of the contents, database or otherwise, the technique is similar.
To illustrate, I'll develop a function for generating three SELECT fields for getting a date
from the user: month, day, and year. To generate a list of the months, it is best to draw
from an array to display their names. Days and years are numbers, so their values and
displayed names are the same. Listing 20.11 demonstrates.


The options for each selector are generated in a for loop. Months range from 1 to 12,
days from 1 to 31. For years, I've chosen to present an 11-year range around the current
year. Notice that if you submit a date, it refreshes the page and sets the form with the date
you chose. The key is the addition of the if statement. Each time through the loop the
current value is tested against the one to be selected.


Listing 20.11 Date Selector

Free download pdf