Database Reference
In-Depth Information
functions that generate form elements automatically perform HTML-encoding, unlike
its functions that create nonform elements.
To produce a list of states for which the values are abbreviations and the labels are full
names, we do need a labels argument. It should be a reference to a hash that maps each
value to the corresponding label. Construct the value list and label hash as follows:
my @state_values ;
my %state_labels ;
my $sth = $dbh -> prepare ( qq{
SELECT abbrev, name FROM states ORDER BY name
} );
$sth -> execute ();
while ( my ( $abbrev , $name ) = $sth -> fetchrow_array ())
{
push ( @state_values , $abbrev ); # save each value in an array
$state_labels { $abbrev } = $name ; # map each value to its label
}
Pass the resulting list and hash by reference to popup_menu() or scrolling_list() ,
depending on the kind of list element to produce:
print popup_menu ( - name => "state" ,
- values => \ @state_values ,
- labels => \ %state_labels );
print scrolling_list ( - name => "state" ,
- values => \ @state_values ,
- labels => \ %state_labels ,
- size => 6 ); # display 6 items at a time
Like CGI.pm, the Ruby cgi module has methods for generating radio buttons, pop-up
menus, and scrolling lists. Examine the form_element.rb script to see how to use them.
However, I don't discuss them here because I find them awkward to use, particularly
when it's necessary to ensure that values are properly escaped or that certain group
members are selected by default.
If you use an API that provides no ready-made set of functions for producing form
elements (or which, like Ruby cgi , is inconvenient to use), you may elect either to print
HTML as you fetch list items from MySQL, or write utility routines that generate the
form elements for you. The following discussion considers how to implement both
approaches, using PHP and Python.
In PHP, to present the list of values from the cow_color table in a pop-up menu, use a
fetch-and-print loop like this:
$stmt = "SELECT color FROM cow_color ORDER BY color" ;
$sth = $dbh -> query ( $stmt );
print ( '<select name="color">' );
while ( list ( $color ) = $sth -> fetch ( PDO :: FETCH_NUM ))
{
Search WWH ::




Custom Search