Unlike the HTML controls we've already seen, HTML listboxes, created with <SELECT> controls, can support multiple selections. For example, take a look at phplistbox.html, Example 5-9, where we're letting the user select his or her favorite fruits. Example 5-9. Listboxes, phplistbox.html<HTML> <HEAD> <TITLE>Using Lists</TITLE> </HEAD> <BODY> <CENTER> <H1>Using Lists</H1> <FORM METHOD="GET" ACTION="listbox.php"> Select your favorite fruit(s): <BR> <BR> <SELECT NAME="Food[]" MULTIPLE="TRUE"> <OPTION>Apple</OPTION> <OPTION>Orange</OPTION> <OPTION>Pear</OPTION> <OPTION>Pomegranate</OPTION> </SELECT> <BR> <BR> <INPUT TYPE="SUBMIT" VALUE="Submit"> </FORM> </CENTER> </BODY> </HTML> The user can select multiple listbox items, as you see in Figure 5-9. Figure 5-9. Using listboxes.We've named the listbox "Food" here, but because multiple selections are possible, we can't just recover the selections using $_REQUEST["Food"]. Instead, we can refer to the first selection, if there is one, as $_REQUEST["Food"][0], the second, if there is one, as $_REQUEST["Food"][1], and so on. To catch them all, we'll use a foreach loop as you see in listbox.php, Example 5-10. Example 5-10. Retrieving data from lists, listbox.php<HTML> <HEAD> <TITLE>Using Lists</TITLE> </HEAD> <BODY> <CENTER> <H1>Retrieving Data From Lists</H1> You selected: <BR> <?php foreach($_REQUEST["Food"] as $fruit){ echo $fruit, "<BR>"; } ?> </CENTER> </BODY> </HTML> The results appear in Figure 5-10, where, as you can see, we're retrieving the selections the user made in a multi-user listbox. Not bad. Figure 5-10. Reading data from listboxes. |