Database Reference
In-Depth Information
print
(
make_scrolling_list
(
"color"
,
$values
,
$values
,
""
,
3
,
FALSE
));
The state list uses labels that differ from the values. Fetch the labels and values like this:
$values
=
array
();
$labels
=
array
();
$stmt
=
"SELECT abbrev, name FROM states ORDER BY name"
;
$sth
=
$dbh
->
query
(
$stmt
);
while
(
$row
=
$sth
->
fetch
(
PDO
::
FETCH_NUM
))
{
$values
[]
=
$row
[
0
];
$labels
[]
=
$row
[
1
];
}
Use the values and labels to generate the type of list you want:
print
(
make_popup_menu
(
"state"
,
$values
,
$labels
,
""
));
print
(
make_scrolling_list
(
"state"
,
$values
,
$labels
,
""
,
6
,
FALSE
));
Ruby and Python implementations of the utility functions are similar to the PHP ver‐
sions. For example, the Python version of
make_popup_menu()
looks like this:
def
make_popup_menu
(
name
,
values
,
labels
,
default
):
result
=
''
# make sure name and default are strings
name
=
str
(
name
)
default
=
str
(
default
)
for
i
in
range
(
len
(
values
)):
# make sure value and label are strings
value
=
str
(
values
[
i
])
label
=
str
(
labels
[
i
])
# select the item if it corresponds to the default value
if
value
==
default
:
checked
=
' selected="selected"'
else
:
checked
=
''
result
+=
'<option value="
%s
"
%s
>
%s
</option>'
%
(
cgi
.
escape
(
value
,
1
),
checked
,
cgi
.
escape
(
label
,
1
))
result
=
'<select name="
%s
">
%s
</select>'
%
(
cgi
.
escape
(
name
,
1
),
result
)
return
result
To present the cow colors in a form, fetch them like this:
values
=
[]
stmt
=
"SELECT color FROM cow_color ORDER BY color"
cursor
=
conn
.
cursor
()
cursor
.
execute
(
stmt
)
for
(
color
, )
in
cursor
: