Using HTML Forms With PHP
By Nicholas Chase
2004-01-09
Reader Rating:

Getting All Form Values
Checkbox fields are just one example of a situation where you may not be entirely certain of the names of form values to expect. Often, you might find it useful to have a single routine that look at all of your form values in a generic way.
Fortunately, because $HTTP_GET_VARS and its ilk are simply hash tables, you can use some of the properties of arrays to manipulate them. For example, you can use the array_keys() function to get a list of all of the potential value names:
Listing 8. Getting a list of form value names
...
$form_fields = array_keys($HTTP_GET_VARS);
for ($i = 0; $i < sizeof($form_fields); $i++) {
$thisField = $form_fields[$i];
$thisValue = $HTTP_GET_VARS[$thisField];
echo $thisField ." = ". $thisValue;
echo "<br />";
}
...
|
In this case, you actually combine several techniques. First, retrieve an array of form field names and call it $form_fields. The $form_fields array is just a typical array, so you can use the sizeof() function to determine the number of potential keys, and loop through each one. For each one, you retrieve the name of the field and then use that name to get the actual value. The result is a Web page that reads:
ship = Midnight Runner
tripdate = 12-15-2433
exploration = yes
crew = Array
|
Notice two important things here. First, the contact field didn't return at all, as expected. Second, the crew value (which is, incidentally, named crew and not crew[], as you might expect) is an array, and not a value. To actually retrieve all values, you'll need to detect any arrays using the is_array() function and handle them accordingly:
Listing 9. Accounting for arrays
...
for ($i = 0; $i < sizeof($form_fields); $i++) {
$thisField = $form_fields[$i];
$thisValue
= $HTTP_GET_VARS[$thisField];
if (is_array($thisValue)){
for ($j = 0; $j <
sizeof($thisValue); $j++) {
echo $thisField ." = ". $thisValue[$j];
echo "<br />";
}
} else {
echo $thisField ." = ". $thisValue;
}
echo "<br />";
}
...
|
The result is all of the data that was actually submitted:
ship = Midnight Runner
tripdate = 12-15-2433
exploration = yes
crew = snertal
crew = gosny
|
First published by
IBM developerWorks
If you found this article interesting, you may want to read these as well:
» Protecting your PHP and HTML Source Code
» Publishing Newsletters Using PHP & MySQL - 4
» Publishing Newsletters Using PHP & MySQL - 3
» Publishing Newsletter Using PHP & MySQL - 2
» Publishing Newsletters Using PHP & MySQL
» Unix Webserver Crontab Basics
|