ÄúµÄλÖãºÑ°ÃÎÍøÊ×Ò³£¾±à³ÌÀÖÔ°£¾PHP ±à³Ì£¾PHP 5 Power programming
Team LiB
Previous Section Next Section

11.5. Form Handling

Building HTML forms by hand is straightforward, but as your demands grow and you need to do input validation, forms that span across multiple pages, or want to use templates, you are better off using a form generator.

HTML_QuickForm is a PEAR package that offers form handling. HTML_QuickForm lets you set up validation rules that are executed on the client or server side, and it integrates with several template systems.

11.5.1. HTML_QuickForm

One of the most common reasons for starting to use a web-scripting language such as PHP is to be able to process online forms. A lot has happened since the <ISINDEX> and <FORM> tags. With form builders such as HTML_QuickForm, managing sites that use forms extensively becomes much easier.

HTML_QuickForm represents each element in the form as an object. For each form element object, you may set client or server validation rules that will be executed automatically.

11.5.2. Example: Login Form

Here is part of a previous example that you may recognize. This piece of code uses HTML_QuickForm to implement a login form:

$form = new HTML_QuickForm('login', 'POST');
$form->addElement('text', 'username', 'User name:', 'size="10"');
$form->addRule('username', 'Please enter your user name!',  'required',
               null, 'client');
$form->addElement('password', 'password', 'Password:');
$form->addElement('submit', 'submit', 'Log In!');
$form->display();

Here, the form is called login and uses a POST request. There are two input elements: username and password. In addition, a client-side "required" validation rule is applied to the username field. A "required" rule makes sure the element is not empty; in this case, a piece of JavaScript code will prevent you from submitting the form until there is something in the "username" field.

11.5.3. Receiving Data

When the POST is submitted, the receiving HTML_QuickForm object automatically loads the POST data. By calling the validate() method, you can ensure that data was posted to the form and that all the validation rules passed. validate() returns TRue if there is data, and it is valid:

if ($form->validate()) {
    $dbh->query("UPDATE users SET lastvisit = ? ".
                "WHERE userid = ?",
                array(time(), $_POST["username"]));
}

    Team LiB
    Previous Section Next Section