PHP Tutorial :: Forms (I)

PHP Example #59

A simple form

This is a fundamental usage of a form. The string that the user types in the text field is stored in the auto-global variable
$_POST['user'] and then sent to this very webpage, where it will be printed as part of the message. While no element exists in
the auto-global array $_POST[] (which means that no input has been made), an initial message is displayed.

PHP Example #60

A simple form

This example works like the previous one, but here the trick is that after sending the string, the form disappears and only the
message is displayed. The auto-global variable $_SERVER['PHP_SELF'] indicates that the string should be returned to the very
webpage that sent it.

Remember that $_SERVER['PHP_SELF'] only works within the scope of PHP source code tags and not in the scope of simple HTML
code, where it is necessary to explicitly write the URL (in this case "php_017.php"), being lost so the flexibility that
the $_SERVER['PHP_SELF'] variable contributes.

PHP Example #61

Accessing parameters in a form

Certain uto-global arrays contain the values of any parameter sent with a form or passed thru an URL. Values that are sent by the
method GET are stored in $_GET while values that are sent by the method POST are stored in $_POST. The query string
?product_id=21&category=fryingpan placed at the end of the URL would set the corresponding values in $_GET['product_id'] and
$_GET['category']. Sending the form below sets the corresponding values in $_POST['product_id'] and $_POST['category'].

From here onwards, the HTML source code of the forms will be included as reference before the PHP source code.

PHP Example #62

Accessing parameters in a form

In a form an element that can have multiple values needs to have a name that ends with []. This forces the PHP interpreter to
treat the multiple values as elements of an array. If the form on this example is sent with two elements selected in the list,
then $_POST['lunch'] turns into an array with two elements, being their values the value attributes of the option elements for
the selected elements.

The HTML source code of the form is included as reference before the PHP source code.