Back to DFS's Workshop Page
Back to Agenda Page
The whole purpose of using forms is to provide options to the user. If all options are known when a form is created on a page, the page can be a static HTML one. If they are not, they need to be gotten from somewhere. This could be a plain file or a data base.
One of the HTML tags which is used in forms to present possibilities to the user is select. The following code is useful if the data will never change.
<select name="year"> <option value="1998">1998 <option value="1999">1999 <option value="2000">2000 <option value="2001">2001 <option value="2002">2002 <option value="2003">2003 </select>
This code produces the following select (drop down) box:
PHP allows you to use a set of values which are determined when the script is executed. Suppose that the set of years the user can choose from is stored in an array called $years. The following code assumes that the number of elements in the array is held in a variable called $numyears and that the subscripts for $years run from 0 to $numyears - 1. $numyears can be assigned a value when the array is being populated.
for( $i = 0; $i < $numyears; $i++) {
echo "<option value=\"";
echo $years[$i];
echo "\">";
echo $years[$i] . "\n";
}
The variable $numyears does not need to be used. A call to the built-in function count() can be used in the for loop.
for( $i = 0; $i < count($years); $i++) {
If the subscripts are not consecutive values starting with 0, the foreach construct can be utilized.
foreach ($years as $year) {
echo "<option value=\"";
echo $year;
echo "\">";
echo $year . "\n";
}
Get to the directory where you are storing your PHP code.
Create a new file called helloworld3.php so that it looks like the following code.
<?php // PHP echoing "Hello World in HTML" // Using a variable // helloworld3.php $title = "Hello World in HTML"; echo "<html>\n"; echo " <head>\n"; echo " <title> . $title . </title>\n"; echo " </head>\n"; echo " <body>\n"; echo " <p>Hello, World!</p>\n"; echo " </body>\n"; echo "</html>\n"; ?>
In your favorite web browser, type
http://localhost/~YOURID/test_php/helloworld3.phpwhere YOURID is the user ID you have on the system.