PHP - Complete Form



This chapter puts all the concepts of form validation and extraction of HTML form data into PHP code. The complete form handling code given below has three sections: A PHP code section in the beginning that looks for any validation errors when the form is submitted, the HTML form with various elements such as text fields, radio buttons, Select control, checkbox, etc.

The third part is again a PHP code that renders the data entered by the user.

PHP Error Tracking

The code that traps errors, is in the beginning of the entire script. Obviously, this will be executed every time the page is loaded.

If it's being loaded after the form is submitted, the following segment checks whether each element is empty, the email field is well-formed, and the checkbox is clicked (indicating that the user agrees to the terms).

HTML Form

The HTML script that renders an entry form, follows the error trapping code. Various for elements have been employed in the form design.

Absolute Classes Registration Form

* required field.

"> *
Name: *
E-mail: *
Time:
Classes:
Gender: Female Male *
Select:
Agree

Note that the form data is submitted back to the same script, hence the form's action attribute is set to $_SERVER["PHP_SELF"] superglobal.

This part also contains certain inline PHP code that flashes the error messages besides the respective form control – such as Name Required message just besides the Name text box, if the name field is empty while submitting the form.

Display Form Data

The third part of the script is again a PHP code that echoes the values of each of the form fields submitted by the user.

Your given values are as :";
      echo ("

Name : $name

"); echo ("

Email address : $email

"); echo ("

Preffered class time : $course

"); echo ("

Class info : $class

"); echo ("

Gender : $gender

"); echo "

Subjcts Chosen:

"; if (!empty($subject)) { echo "

    "; for($i = 0; $i < count($subject); $i++) { echo "
  • $subject[$i]"; } echo "
"; } } ?>

Here's the sample data filled in the form when the script is run from the server's document root folder −

PHP Complete Form 1

When submitted, the output is rendered as below −

PHP Complete Form 2

Handling HTML Form

The complete code of PHP's handling HTML form is as follows −



   


   
   

Absolute Classes Registration Form

* required field.

"> *
Name: *
E-mail: *
Time:
Classes:
Gender: Female Male *
Select:
Agree
Your given values are as :"; echo ("

Name : $name

"); echo ("

Email address : $email

"); echo ("

Preffered class time : $course

"); echo ("

Class info : $class

"); echo ("

Gender : $gender

"); echo "

Subjcts Chosen:

"; if (!empty($subject)) { echo "

    "; for($i = 0; $i < count($subject); $i++) { echo "
  • $subject[$i]"; } echo "
"; } } ?>

It will produce the following output

PHP Complete Form 1
Advertisements