HomePHP Page 8 - PHP 101 (part 3) - Chocolate Fudge And Time Machines
Checking The Boxes - PHP
After teaching you the fundamentals of form processing, PHP 101 returns with an explanation of WHILE, FOR and FOREACH loops, those PHP constructs that can save you hours of unnecessary HTML coding. Also included: array variables, the auto-increment operator, and some yummy desserts.
In addition to their obvious uses, arrays and loops also come in handy when processing forms in PHP. For example,
Here's a simple example which demonstrates how arrays can be used when processing checkboxes in an HTML form:
<html>
<head>
</head>
<body>
<?
// check for $submit
if (!$submit)
{
//
and display form
?>
<form action="jukebox.php4" method="GET">
<input type="checkbox"
name="artist[]" value="Bon Jovi">Bon Jovi
<input type="checkbox" name="artist[]"
value="N'Sync">N'Sync
<input type="checkbox" name="artist[]" value="Boyzone">Boyzone
<input
type="checkbox" name="artist[]" value="Britney Spears">Britney Spears
<input
type="checkbox" name="artist[]" value="Jethro Tull">Jethro Tull
<input type="checkbox"
name="artist[]" value="Crosby, Stills &
Nash">Crosby, Stills & Nash
<br>
<input
type="submit" name="submit" value="Select">
</form>
<?
}
// or display
the selected artists
else
{
?>
<b>And here are your selections:</b>
<br>
<?
//
use a "for" loop to read and display array elements
for($count = 0; $count <
sizeof($artist); $count++)
{
echo "<i>$artist[$count]</i><br>";
}
}
?>
</body>
</html>
In this case, when the form is submitted, PHP will automatically create an array
variable named $artist, and populate it with the items selected. This is useful when you need to group related form data together.
The same technique can be applied to "multiple select" list boxes:
<html>
<head>
</head>
<body>
<?
// check for $submit
if (!$submit)
{
//
and display form
?>
<form action="jukebox.php4" method="POST">
<select
name="artist[]" size="6" multiple>
<option value="Bon Jovi">Bon Jovi</option>
<option value="N'Sync">N'Sync</option>
<option value="Boyzone">Boyzone</option>
<option value="Britney Spears">Britney Spears</option>
<option value="Jethro
Tull">Jethro Tull</option>
<option value="Crosby, Stills & Nash">Crosby,
Stills & Nash</option>
</select>
<br>
<input type="submit" name="submit"
value="Select">
</form>
<?
}
// or display the selected artists
else
{
?>
<b>And
here are your selections:</b>
<br>
<?
// use a "for" loop to read
and
display array elements
for($count = 0; $count < sizeof($artist); $count++)
{
echo "<i>$artist[$count]</i><br>";
}
}
?>
</body>
</html>