PHP Tutorials

Program Input and Output

Without input and output, your program might as well be a regular HTML page. When you add input and output, however, your program’s potential will be unlimited. You will be able to collect information from your visitors, ask them questions, and give them a personalized experience that you never could have provided before.

This chapter teaches you the following:

The purpose of input and output

Output as you’ve already seen it

Advanced types of output

Requesting input

Input methods

Filed under: Chapter 3 @ 10:27 pm

Revisiting Output

Revisiting Output
Output is the text or information that is sent from your program to the user (specifically, the visitor to your Web site). Think of output as anything the user receives from a program.

For example, when you use a search engine, a program performs the search and sends back HTML data that looks to your browser like any other HTML page. The page isn’t like other HTML files—it isn’t saved anywhere on the server. The program simply sent its output—a customized HTML page—straight to your browser.

Figure 3.1 illustrates the interaction that might occur between your browser and a server when performing such a search.

Figure 3.1. At its most basic level, the interaction between a visitor’s browser and your program works like this: A request is sent to the program and the program’s output is its response to the browser.

We’ve already briefly visited one way of sending output—the echo command. Output can be sent in several different ways. The method that you use depends on the context within the program. The following considerations may influence your decision on which method to use:

The content may vary from one visitor to the next, or it may always be the same.

The length of the content you wish to send as output might be short (one line or a single word), or it could be long (a paragraph, a table, or even a whole file).

The following sections will help you understand when and how to use each method of output.

The echo Command
You should decide which method to use to send output based on what you’re sending. You must decide whether the content is static or dynamic. On top of that, if the content is dynamic, you will have to consider how much of it there is to send.

All output can be divided into two main categories: static and dynamic. Static output is output that will not change from visitor to visitor; it is hard-coded within the file and independent of any variables. Dynamic output, on the other hand, is any output that contains variables, may change from visitor to visitor, or depends upon variables in any way.

To help clarify the division, think of it this way: Static output will never change unless someone changes the program itself; dynamic output will change from user to user, from one time to the next, or depending on an outside data source such as a database. Figure 3.2 illustrates this visually.

Figure 3.2. The left side of this diagram shows the interaction between multiple visitors and a program that produces static output; the right side shows multiple visitors interacting with a program that produces dynamic output.

The echo command is an excellent choice for dynamic content. It allows you to output numbers, text, and variables all in one string. While it can be used for static content as well, your HTML code will become less readable if you have to “wrap” it with PHP code (such as enclosing it in quotes). Therefore, echo should only be used to insert small amounts of dynamic content at a time.

The following example demonstrates a PHP program with nothing but static output—it is returned just as a regular HTML file would be



<html>
<head><title>Example Page</title></head>
<body>This is an example!</body>
</html>

Since none of this code is enclosed in PHP tags, every line is sent as output. Also, the output doesn’t rely in any way on any variables or data sources, so it is classified as static.

NOTE

Recall from Chapter 1, “Welcome to PHP,” that anything outside of PHP tags is sent straight to output without being processed in any way. Even if a variable is inserted into this code, it would not be interpreted as a variable; rather, the text would be sent just as it appeared.

The following program sends the same result (also static output), but this time uses echo:



<?php
/* ch03ex01.php – demonstrates static output with echo */

echo "<html>\n";
echo "<head><title>Example Page</title></head>\n";
echo "<body>This is an example!</body>\n";
echo "</html>\n";

?>



NOTE

The \n is interpreted as a symbol (called an escape sequence); it means newline and is sometimes also called the newline character. It is comparable to pressing Enter on your keyboard. Without the newlines, all of the outputted HTML code for the previous example would appear on a single line because echo alone doesn’t add anything to separate the lines.

This example uses echo in a way that is understandable to PHP but more complicated than most people prefer to read. Look at the first example and then again at the second; in this case, there’s no good reason to add all of the extra echo commands, quotes, and newline characters.

Also, according to our basic classification of echo, it should only be used for short, dynamic output. Since this output is long and static, it would be better to stick with the method used in the first example by placing the text outside of the PHP tags.

Now let’s take a look at a more appropriate use of echo. The following example is a mostly static HTML page with a small portion of dynamic content—therefore, a small section of PHP code and an echo statement are inserted to output the contents of a variable ($aVariable):



<?php
/* ch03ex02.php – demonstrates dynamic output with echo */

$aVariable = "This is a variable!";

?>
<html>
<head><title>Example: Static vs. Dynamic Output</title></head>
<body>

<b>Static output:</b>

The following is static output. It will never change.

Here's a variable: $aVariable



<b>Dynamic output:</b>

The following is dynamic output. It may change.

<?php

echo "Here's a variable: $aVariable";

?>

</body>
</html>

Here's the output:

<html>
<head><title>Example: Static vs. Dynamic Output</title></head>
<body>

<b>Static output:</b>
This is static output. It will never change.

Here's a variable: $aVariable



Dynamic output:

This is dynamic output. It may change.

Here's a variable: This is a variable!

</body>
</html>


NOTE

This output is the HTML code you would see if you used your browser’s View Source feature.

The only text the user would actually see in his browser would be

Static output:
This is static output. It will never change.
Here’s a variable: $aVariable

Dynamic output:
This is dynamic output. It may change.
Here’s a variable: This is a variable!

From the previous example you should recall that PHP doesn’t interpret text placed outside of the PHP tags at all. So, the text “$aVariable” was output just as it appeared in the code when it was outside of the PHP tags. However, when it was mentioned inside the tags in a double-quoted string it was interpreted as a variable and the value of that variable was output instead of the actual text “$aVariable.”

This is a more appropriate use of echo; notice that only a single line (the one with the variable) was sent with echo. The rest of the output was sent as static output. It will never change and therefore doesn’t need echo.

CAUTION

If the strings following echo in the previous example had been single quoted, they would not have been interpreted, and the static output and dynamic output would look the same.

Using Here-doc
So far you’ve seen output sent by placing it outside of the PHP tags and output sent using one-line echo statements. Now lets take a look at ways to send large amounts of dynamic output without the tediousness and confusion of using multiple echo statements. This is important: In the future, you might find yourself writing programs in which more than 75% of the program is dynamic output.

There are two ways to send large amounts of dynamic output: Use a single echo statement, thereby reducing the clutter of outputting multiple lines of data with echo, or use static output and insert PHP tags to print variables wherever necessary.

The first method is called here-doc (short for “here-document”). Here-doc helps you, the programmer, create clearer multiline strings; it behaves just as a double-quoted string would, but in a more readable fashion. It also allows you to use only one echo statement, as opposed to the clutter of repeated echo statements.

PHP understands and executes the following code, but because the string might not end for many lines and because any double quotes within the string must be escaped, the purpose and contents of the string can become unclear:



<?php
/* ch03ex03.php – demonstrates multi-line double-quoted string */

// Multi-line double-quoted string
echo "<html>
<head><title>Example</title></head>
<body>
This is an example!
</body>
</html>";

?>


Here-doc allows the code to use more understandable multiline strings. First, by using here-doc, you’re saying, “Heads up! I’m using a multiline string here.” If you take a look at the double-quoted string shown previously, that’s not suggested in any way; in fact, if you saw the following line alone, you would think that it was erroneous:



echo "<html>

Using double quotes to create multiline strings is hard to understand just for this reason. There’s nothing to say that the string is multiline other than the fact that it isn’t ended with a double quote. You or someone reading your code might find themselves asking, “Did he mean to do that?”

There’s another reason that here-doc is better than double quotes. Whereas, the double quote at the end of a multiline string doesn’t mean much to anybody except “this is the end of a string,” here-doc allows you to specify an end identifier that can be descriptive of the string’s purpose or contents.

Here’s an example of a here-doc statement:






<?php
/* ch03ex04.php – demonstrates use of here-doc */

// Set $user and $pass variables
$user = "John Doe";
$pass = "doe123";

// Outputting a multi-line here-doc string
echo <<<END_USER_INFO
Username: $user

Password: $pass
END_USER_INFO;

?>



The <<< syntax is used exclusively for here-doc. The first line might be read: "echo everything until END_USER_INFO is reached."

NOTE

END_USER_INFO just happens to be the end identifier I chose; while it is appropriate for its descriptiveness of the string, it could have been any other string following the end identifier naming convention, which follows.

Like constants and variables, end identifiers for here-doc strings follow a naming convention. Typically, they are uppercase strings with any multiple words separated by underscores. The convention itself dictates that identifiers can be any combination of letters (upper- and lowercase), numbers, and underscores. However, an end identifier should not contain spaces or begin with a number.

Notice that here-doc strings are interpreted just as double-quoted strings are: Variables are replaced with their values and escape sequences (such as \n) still work.

NOTE

Double quotes in here-doc strings can be escaped, but it isn't necessary as it is in a double-quoted string.

You must place the ending identifier for a here-doc string at the very beginning of a new line. This makes here-doc strings more efficient for PHP to interpret because PHP only has to look for the end identifier at each new line as opposed to every position of every line. However, if you forget to place the end identifier at the leftmost position on a line, you will find yourself trying to figure out an error message for a line that seems to have nothing wrong with it; in fact, it probably doesn't. Make sure any here-doc statements before it are terminated correctly. Remembering this can save you much frustration.

Take a look at the following code, which directly compares the use of a double-quoted string to a here-doc string:



<?php
/* ch03ex05.php – compares use of double-quoted string to here-doc */

// Multi-line double-quoted string
echo "<body bgcolor=\"#FFFFFF\" text=\"#000000\">
This is an example!

Here's a variable: $aVariable


</body>";

// Multi-line here-doc string
echo <<<END_OF_OUTPUT
<body bgcolor="#FFFFFF" text="#000000">
This is an example!

Here's a variable: $aVariable

</body>
END_OF_OUTPUT;

?>


These examples have the exact same output. However, you should notice how difficult it could be to read a multiline string when the double-quotes must be escaped. With too much escaping, your strings would, at times, become almost impossible to comprehend. Since here-doc doesn’t require quotes to be escaped, it can make your code easier to read.

Using Short Tags
The other method of outputting large amounts of dynamic data is to use short tags. As discussed in Chapter 1, short tags are a shorthand way to make regular PHP tags shorter.

The following example uses the short tag that you’ve already seen:


<? echo "This echo statement is in short tags!"; ?>

NOTE

Recall from Chapter 1 that using short tags shortens the first tag because you remove the letters “php” from it; the closing tag remains the same. Also, the semicolon following the command shown here can be omitted because it is the only command within the PHP tags.

Using an echo statement for every dynamic element you wish to output works, but it’s still a bit tedious to type “echo” every time. During the development of PHP, some PHP programmers were migrating to PHP from ASP (Microsoft’s scripting environment known as Active Server Pages, which is somewhat similar to PHP). These programmers were used to ASP tags, which come in two varieties: the regular ASP tags, which, like PHP tags, separate ASP code from static output; and the ASP equals tag. The ASP equals tag added an equals sign to the opening ASP tag (hence the name “equals tag”) and eliminated the need for an explicit command to print output.

PHP has a second short tag that was modeled after ASP’s equals tag. Like ASP’s equals tag, it shortens the amount of code it takes to output a value and eliminates the need for the echo statement by appending an equals sign to PHP’s short tag.

NOTE

Remember that short tags must be enabled in PHP’s configuration file for them to work. The short tag and the short equals tag are collectively classified as PHP’s “short tags.” If you experience problems or short tags don’t work as expected, consult the configuration section of the PHP manual.

Take a look at the following excerpt, which puts PHP’s short equals tag to use:


<?= "This is outputted automagically by the short equals tag!" ?>

Where the letters “php” would appear in a regular PHP tag, there is now an equals sign.

CAUTION

The equals sign must be directly attached to the tag—spaces separating the equals sign from the question mark are not allowed. Also, the short equals tag does not work with the regular PHP tag: Combining

Now that you understand the basics of the short equals tag, let's take a look at its advantages. The short equals tag can significantly reduce the complexity of your code and increase its readability. Take a look at the following code segment, which doesn't use the short equals tag:



<?php
/* ch03ex06.php – demonstrates code using standard PHP tags with echo */

$title = "Example Title";
$text = "Here's some text!";

?>
<html>
<head><title><?php echo $title; ?></title></head>
<body><?php echo $text; ?></body>
</html>

Now compare it to the simpler version of the same code:

<?php
/* ch03ex07.php – demonstrates short equals tag */

$title = "Example Title";
$text = "Here's some text!";

?>
<html>
<head><title><?= $title ?></title></head>
<body><?= $text ?></body>
</html>



While both of these have the same output, the second one is quicker and easier to type. In fact, many developers prefer it to the tediousness of the first method.

CAUTION

Of these two methods, I will use the latter throughout this book to keep my code concise and as clear as possible. However, before adopting the short tags for use on any major project, you should ensure that your host will allow you to use short tags so you don’t run into problems if your host has short tags disabled for some reason.

Here-doc Versus the Short Equals Tag
To summarize the differences between using here-doc or the short equals tag, here-doc can be handy in certain instances (like storing a long string to a variable), but it isn’t usually a very good way to send output. For clarity, it’s probably wiser to stick with the short equals tag or even regular PHP tags with an echo statement, if necessary. However, if you absolutely are stuck on using multiline strings to send output, here-doc is a better way to do it than double-quoted strings, stylistically.

So you can compare the two for yourself side-by-side, the following account information program has been provided using each method. The output is the same for both examples; a program like this would typically be used on an e-commerce or members-only site to tell the user important information about his account, such as his account number and the e-mail address he registered with.

Here’s the here-doc version:




<?php
/* ch03ex08.php – displays account info using here-doc */

// Set up example account information
$user_name = "John Williams";
$user_email = "johnw@example.com";
$user_acctno = 1152;

// Display account info code
echo <<<END_HTML
<b>Name:</b> $user_name

<b>E-Mail:</b> $user_email

<b>Account Number:</b> $user_acctno

END_HTML;

?>


And here’s the short equals tag version of the same program:




<?php
/* ch03ex09.php – displays account info using equals tags */
// Set up example account information
$user_name = "John Williams";
$user_email = "johnw@example.com";
$user_acctno = 1152;

// Display account info code
?>
<b>Name:</b> <?= $user_name ?>

<b>E-Mail:</b> <?= $user_email ?>

<b>Account Number:</b> <?= $user_acctno ?>

<?php

// This space can be omitted, but is included to show that
// more code could be included here if desired.

?>


Filed under: Chapter 3 @ 10:28 pm

Program Input

Program Input
On the Web, input—any data your program needs to process or know in order to perform its task—is gathered from an HTTP request. An HTTP request occurs whenever a user types in an address, clicks a link, or clicks a button on a Web page. The request contains information about the request, such as the desired file, any cookies that have been sent to the browser for that site, and any form fields that are being submitted to the server.

The request can be very complicated, however. Since PHP was created with Web programming in mind, it makes gathering this information less complex.

You still have to know a few things about the HTTP request because PHP divides the input it receives into the categories based on how they arrive in the HTTP request. Input is divided into three main categories: get, post, and cookie variables. You must know which category your variables are in to be able to access them.

NOTE

There is a more direct shortcut for accessing variables discussed later in this chapter, along with its advantages and disadvantages. However, make sure you understand this material before you try to use the shortcut.

For now, don’t worry about the cookie variables category; it will be covered in Chapter 17, “Putting It All Together.”

Get and Post Form Methods
You may recognize the other two categories, get and post, from your previous HTML experience; they are attributes used in the method tag of a form. Depending on which sort of form you use, you will need to use the corresponding category in PHP.

Get forms are commonly used for search queries and small amounts of information that may be exposed in the address bar of the visitor’s browser. A get request is also made whenever a user clicks a link.

CAUTION

You should not use a get form when requesting a visitor’s password or other sensitive information. Items from a get form will be in plain sight of anyone within sight of the visitor’s monitor.

When information is sent to the server in a get request, PHP puts all of the form fields and their values in the appropriate input array, $HTTP_GET_VARS. So, to get the value of a field, use the value of $HTTP_GET_VARS with the field name as the key.

Let’s take a look at an example. The following program generates a personalized greeting for a visitor:



<?php
/* ch03ex10.php – shows personalized greeting form */
?>
<html>
<head><title>Welcome!</title></head>
<body>

<form action="ch03ex11.php">

What's your name? <input type="text" name="userName">
<input type="submit" value="Continue">

</form>

</body>
</html>

Since the form’s method isn’t specified and get is the default method, get is assumed. The PHP file can then find the value for the field in $HTTP_GET_VARS[’name’], as shown in the following file:



<?php
/* ch03ex11.php – shows personalized greeting */
?>
<html>
<head><title>Welcome!<title></head>
<body>
<h4>
Welcome, <?= $HTTP_get_VARS['name'] ?>!</h4>
</body>
</html>


The username and password are shown to the user just as they were entered on the form.

Now let’s take a look at using links to make get requests. When I refer to links, I’m not just referring to the HTML tag. I’m also referring to addresses typed directly into a browser’s location bar or the address specified in an tag.

To investigate this further, let’s create a single-question survey. The question, which could be inserted anywhere in an HTML file, should be set up similar to this:



<?php
/* ch03ex12.php – survey form */
?>
<html>
<head><title>Survey</title></head>
<body>

Which animal do you like better?
<a xhref="ch03ex12.php?answer=dogs">Dogs or
<a xhref=" ch03ex12.php?answer=cats">Cats</a>

</body>
</html>

Upon clicking one of the links, the visitor is taken to answerSurvey.php, which looks like this:



<?php
/* ch03ex12.php - handles survey answers */
?>
<html>
<head><title>Your Answer</title></head>
<body>

You said you like <?= $HTTP_GET_VARS['answer'] ?> the best!

</body>

As you can see, get requests are handled precisely the same as those made with forms. You can also change the question file so that the answer is collected using a form instead of a link. Try this for practice.

Now that you know about get forms, let’s take a look at the other form method. Post forms are used for larger amounts of data (such as detailed user information, e-mail messages, or file uploads) and data that should not be visible in the browser’s address bar (such as passwords). An example of data being clearly visible in the browser’s Address bar is given in Figure 3.3.

Figure 3.3. Sensitive information in a get request may be revealed in a browser’s Address bar.

Let’s try a practice problem. Yahoo!, Hotmail, and Excite all offer private services which require a username and password. In order to verify that a user is really the user he claims to be, services such as these must check that the login name and password are valid. For now, we’ll just focus on collecting the data. The process of actually verifying the information is a separate concept, which will be discussed at various times later in this book, particularly in Chapter 6, “The if, elseif, and else Statements,” and Chapter 13, “Creating Dynamic Content with PHP and a MySQL Database,” when we discuss if statements and using databases, respectively.

The program will have two files: one to request the user’s username and password and a second to retrieve that data.

The first file will contain a form that has its method set to post. If we don’t set the method attribute, the username and password will be left out in the open in the user’s address bar, which is considered to be a security risk. Anybody that happens to walk by the visitor’s computer can see the password in the browser’s Location or Address bar. Figure 3.3, shown previously, shows this vulnerability.

Here’s the first file:




<?php
/* ch03ex13.php – login form */
?>
<html>
<head><title>Authorization Required</title></head>
<body>

<form action="ch03ex14.php" method="post">

Username: <input type="text" name="username">

Password: <input type="password" name="password">

<input type="submit" value="Login">

</form>

</body>
</html>

That’s not too complicated; it’s just an HTML page with a form. Now we need to set up the file to accept the data this form posts. For now, we’re going to set up our program to show the visitor the username and password he entered. To do so, we’ll use the contents of the $HTTP_POST_VARS array because the information was posted with the post method.

Here’s the second file, which handles the data posted from the first file:



<?php
/* ch03ex14.php - shows the visitor what username and password he entered */
?>
<html>
<head><title>Enter your password</title></head>
<body>

Username: <?= $HTTP_POST_VARS['username'] ?>

Password: <?= $HTTP_POST_VARS['password'] ?>

</body>
</html>



This should look a lot like the $HTTP_GET_VARS example did; the only difference is that we’ve changed the method for the form, so we have to change which array we use in PHP—the two (the value of the form’s method tag and the name of the script’s input variable) must always correspond with one another.

For practice, try modifying this program to use get as the method.

TIP

You’ll need to modify both files in order to make it work with the get method.

Once you’ve modified it and it’s working, look at the address in your browser’s Address or Location bar after you’ve posted the form. You should notice a string (such as “?username=joe&password=joepass”) appended to the end of the filename. This is another illustration of why get forms and passwords aren’t a good mixture.

Using Forms
Although creating HTML forms isn’t technically a part of PHP, it is definitely a part of learning PHP. Since forms are just about the only way for your program to collect information from the user, you must use the form elements allowed by HTML to construct the most intuitive form possible.

TIP

The intuitiveness of a form is the overall effectiveness it has for the user. For example, using a single-line text input where the user will probably be entering a large amount of text makes it difficult for the user to read and edit what he’s typing. In that case, it would be more effective to use a textarea.

The various form-input types will be discussed to help you create the most intuitive forms, which in turn makes your visitors experience more pleasing.

Form inputs allow the user to enter text and make selections. For example, if you wish to ask a user for his name, a simple text input is fine. The text input follows this syntax:




<input type="text" name="field_name" value="default_value">


The value attribute is optional; in most cases, it would be left blank. However, if you wish to suggest a value for the user’s input, you can include the value=”default_value” attribute and the value will appear in the field.

For example, to suggest a default value using a variable you already have (such as one that was entered from a previous form), you can specify the value attribute by outputting the variable’s value with short equals tags, like so:



<?php
/* ch03ex16.php – default value example */

// Assume $user_name can come from a previous form submission;
// it's specified here for clarity.
$user_name = "John Doe";
// Print a form using this name as the default value for the user_name field
?>

<form>
<b>Name:</b> <input type="text" name="user_name" value="<?= $user_name ?>">

<input type="submit">
</form>



NOTE

Assuming PHP has its default configuration, you should be able to set the action attribute of this form to the name of the program file (such as ch03ex16.php) and the value of the field would be updated as the default value every time the submit button is clicked.

This example is primarily here to demonstrate that you can specify a dynamic default value, just as any other output can be dynamic.

There are several types of inputs for making selections. We’ll look at radio and check box inputs first, then compare them to select inputs.

The radio input is used to ask the user to pick one item out of a list. The syntax follows this form:



<input type="radio" name="field_name" value="field_value">


In this case, the value attribute is not optional; if you don’t specify it, the field will appear to be blank from within PHP, even if the option is selected. This type of input is best used in groups; the following example could be used to ask a visitor what his favorite pet is



What's your favorite pet?

<input type="radio" name="favorite_pet" value="dog">Dog

<input type="radio" name="favorite_pet" value="cat">Cat

<input type="radio" name="favorite_pet" value="camel">Camel

<input type="radio" name="favorite_pet" value="none">None


Notice that all of the inputs have the same name; this is a feature of the radio input that allows the user to choose only one option, but it only works if the radio buttons all use the same name.

If you wish to get multiple answers from a user, you would need to use a check box input, which follows this syntax:



<input type="checkbox" name="field_name" value="field_value" checked>


Again, the value attribute must be included with this input. However, the checked attribute you see at the end of the tag is optional; if it’s included, the check box will appear checked by default.

This type of input is commonly seen when you sign up for newsletters and free services online. These services gather information about the users they have so they can charge their advertisers more for targeted advertising. The following example demonstrates the common question, “What magazines do you subscribe to?”




What magazines are you currently subscribed to?

<input type="checkbox" name="us_news" value="true">US News
<input type="checkbox" name="sports_illustrated" value="true">Sports Illustrated
<input type="checkbox" name="national_geographic" value="true">National Geographic
<input type="checkbox" name="time" value="true">Time

Notice that all of the name attributes are different; they cannot be the same or multiple selections would overwrite each other and only the last one would be retrievable from within PHP.

The select field allows similar data collection, using a smaller space. For example, listing all of the countries for the user to pick one could take up a lot of space on your form, making it seem longer than it really is. By putting all of the countries into one select input, the long list is compressed into one line. The syntax for a select input is



<select name="field_name" size="field_height" multiple>
<option value="option_value">option_text</option>
...
<option value="option_value">option_text</option>
</select>


The value attribute is optional; if it is omitted, the text used for option_text will be used as the value as well (but option_text never overwrites a value specified in option_value). The multiple attribute is also optional; leaving it out forces the user to pick only one option. If specified, the size attribute determines how many options are visible at once. If the size is omitted, the input appears as a drop-down list; otherwise (if it is specified), the list appears in a scroll box.

Here’s a very short example that could be used to ask a user what country he is from:



What country do you live in?
<select name="country">
<option>China</option>
<option>France</option>
<option>Germany</option>
<option>United Kingdom</option>
<option>United States</option>
</select>

Notice that the multiple attribute wasn’t included because you only want to allow the user to pick one country. Also, the value attributes were omitted because the text found between the two option tags is all you need to know. (The value tags are often used to associate numeric codes that the program understands with textual names that the visitor understands.)

It’s not always appropriate to limit the user to just one selection. To allow multiple selections, the multiple attribute must be specified. Once it is, the user can make multiple selections using Ctrl and Shift. The following input asks the user about his hobbies:



What are your hobbies?

<select name="hobbies[]" multiple>
<option>Travel/Sightseeing</option>
<option>Automotive/Cars/Hotrods
<option>Sports/Fitness</option>
<option>Reading</option>
<option>Outdoors/Camping/Fishing</option>
</select>



This input allows the user to select from zero to all of the options given.

CAUTION

Notice the brackets in the name attribute; since they are present, the hobbies variable in PHP will be an array, with each element being an element selected from the options list. If the brackets were left out, only the last option selected would be visible within PHP.

Let’s say Automotive and Reading are the two options chosen from this list, and the form is submitted. In this case, the $hobbies array contains

Array(
[0] => “Automotive”,
[1] => “Reading” )

The last method for gathering information is the textarea. The textarea is used to allow the user to type a large amount of text, such as a feedback message. Here is the basic syntax for a textarea field:



<textarea name="field_name" rows="field_height"
cols="field_width">default_value</textarea>

Although the rows and cols attributes are optional, it’s best to specify them. You need to experiment a little with these to get a feel for how they affect the size of the textarea. The default_value shown between the beginning and ending tags shows where you can suggest a default value for the textarea to contain. Because the textarea allows for multiple paragraphs, adding a value attribute is not appropriate; this is why the default value is specified between the textarea’s opening and closing tags. If you chose to omit the default value, you still need to include the closing tag.

There are two inputs to submit a form: submit and image. These inputs work about the same way, except the latter uses an image instead of a gray button.

Here’s an example of each; these two uses are functionally equivalent:




<input type="submit" value="Submit">
<input type="image" xsrc="/path/to/image.gif">

Your forms must always include a submit button or the form won’t be very effective. Pressing Enter or using JavaScript works most of the time, but it’s always preferable to have a button for those who can’t use Enter or don’t support JavaScript.

You might want to use this section as reference until you get used to creating forms (if you’re not already used to it). With some practice, you’ll have no trouble at all creating intuitive forms.

Filed under: Chapter 3 @ 10:31 pm
Next Page »

Powered by WordPress