11 - Working with forms in PHP

Forms are the basic interface between user and server. Form handling is the very basic and important feature of PHP. For form creation, we should use HTML. Using forms we can accept data from user and then we can handle the data using PHP. Data can be saved in any database server like MySql.

Creating forms in PHP using HTML

While creating forms in PHP using HTML we should keep some points in our mind:

  • We should specify a unique name for every entry element like (form, textbox, password box, select, text area etc.), for this we can use Name attribute.
  • We should specify Value rather than HTML default value.
  • We can pass hidden variables from form to form using Hidden data entry elements.

Example: helloform.html

<html> 
 <head> 
 </head> 
 <body> 
  <form method="post" action="helloresponse.php"> 
    Your name:<input type="text" name="my_name"> 
  <br/> 
    <input type="submit" value="Say Hello"> 
  </form> 
 </body> 
</html>

The above code will display form as:

When user submits form without any name, then the output will be:

And when user submits form after entering value, the output will be:

 

Server variables:

There are some useful server variables apart of PHP_SELF and $_SERVER, those can be used to provide information on the web server and the current request. Such as:

Element

Description

QUERY_STRING

It is used to contain the part of URL after the question mark.

PATH_INFO

It is used to contain extra path information tacked onto the end of the URL after a slash. This can be used to pass information to a script without using query string.

SERVER_NAME

It is used to contain the name of the web site on which the PHP is running or it can contain the name of domain that is being used.

 

How to pass Information using form

There are two different ways of passing information between browser and server. GET and POST

These methods are used in form tag as:

    <form method=”GET”> and <form method=”POST”>

If GET method is used to pass parameters, it will be encoded in the URL which is also called query string. Form parameters can be anything

There are two steps included in form handling:

· Form display

In this step firstly user sends a request to server to display form. For this user can enter the URL of web page. Web server will verify the web page and revert it to the client machine.

· Form processing

After display form on client machine, user can enter values in form. When the form is submitted, it is validated and processed at server side.

Example: Calculator

Main.html

<form action="cal.php" method="POST"> 
  Enter First Number:<input name="s_no" type="text"></br></br>
  Enter second Number:<input name="e_no" type="text"><br></br>
  Select your choice: 
  <select name="D1"> 
   <option>+</option> 
   <option>-</option> 
   <option>*</option> 
   <option>/</option>
   <option>%</option> 
  </select> 
  <input type="submit" name="B1" value="Submit"> 
</form>

Form will look like this:

Calc.php

<?php 
  $a=$_POST["s_no"]; 
  $b=$_POST["e_no"]; 
  $op=$_POST["D1"]; 
  if($op=="+") 
  {     
     $res=$a+$b;     
     echo "Addition of numbers is:$res"; 
  } 
  if($op=="-") 
  {     
     $res=$a-$b;     
     echo "Subtraction of numbers is:$res"; 
  } 
  if($op=="*") 
  {     
    $res=$a*$b;     
    echo "Product of numbers is:$res"; 
  } 
  if($op=="/") 
  {     
    $res=$a/$b;     
    echo "Division of numbers is:$res"; 
  } 
  if($op=="%") 
  {     
    $res=$a%$b;     
    echo "Modulus of numbers is:$res"; 
  } 
?>

 

The output will be:

 

Example: contact.html

In the above simple contact form, we have used POST method to transfer complete form data in php file. In our form we have used one textbox, one password box, three radio buttons and one submit button.

Apart of these we have used one textarea also to accept comments from user.

We will save this file with the name contact.html

When we send data to myContact.php file, we can access all these values there. All variables are passed to php file using POST method and stored in associative array $_POST.

In the $_POST associative array all the variables can be mapped as follows:

Variable

Holds value of

$_POST['yourname']

text field "yourname"

$_POST['email']

text field "email"

$_POST['likeit']

selected radio box group "likeit"

$_POST['comments']

textarea "comments"

 

The output of above form will be:

When user will enter the values in form and press Send it! Button all the contents will transfer to myContact.php file

We can display the contents of form using following script:

<html>
 <header>
 </header>
 <body>
   Your name is: <?php echo $_POST['yourname']; ?><br />
   Your e-mail: <?php echo $_POST['email']; ?><br />
   <br />
     Do you like this website? <?php echo $_POST['likeit']; ?><br />
   <br />
   Comments:<br />
   <?php echo $_POST['comments']; ?>
 </body>
</html>

Output after submission of form:

Self Submission

Self submission refers to the process of combining one or more forms and form handlers in a single script, using the HTML form.

Self submission of form can be used when there is need to submit the same form more than once. Self submission causes fewer clicks throughout submission process. Separate form and form handler make it difficult to pull data from the database, editing and submitting the form is also difficult. Self submission is accomplished by the simplest of means: we should specify the same script name as the ACTION target in the FORM element as:

     <FORM METHOD=”POST” ACTION=”myself.php”>

     OR

     <FORM METHOD=”POST” ACTION=”<?php echo $_SERVER[‘PHP_SELF’];?>”>

The most important thing in self submission is that logic comes before the display.

Example:

<?php
  if(isset($_POST['submit'])) 
  { 
    $name = $_POST['name'];
    echo "<font color=blue>User Has submitted the form and entered this name : <b> $name </b></font>";
    echo "<br/>";
    echo "<br><font color=Red>You can use the following form again to enter a new name.</font>"; 
  }
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    Please Enter Your Name: <input type="text" name="name"><br>
   <input type="submit" name="submit" value="Submit Form"><br>
</form>

Output of above code is:

 

Editing data with an HTML Form

The most important task that we can do with PHP is, we can pull data from database, display it on form and it can be edited by user and then we can save these updated contents in database. To accomplish this task there are various form elements are found in HTML such as:

Text and Textarea

         These elements are the simplest elements; there is only one possible Value per Name

Checkboxes

         The Checkbox type has only one possible value per input: it can be off or on. The database field which can be used to display this type of information may be of small integer or bit type of value with 0 or 1 for unchecked and checked values.

 Radio Buttons

         Radio buttons contain one-to-many type relationship. They may have multiple possible values, but only one can be pre-displayed or pre-selected. As compare to text field or checkbox radio buttons are difficult to display information pulled by a database.

 Select

          Select field is the most easiest to use. It can handle the largest number of options, it can also allow the user to select multiple options that can be passed back to the database using arrays.

Example:

<html>
  <head>
    <title>PHP form select box example</title>
    <style>
      label,a 
      {
        font-family : Arial, Helvetica, sans-serif;
        font-color:blue;
        font-size : 12px; 
      }
    </style>    
  </head>
  <body>
    <?php
      if(isset($_POST['formSubmit'])) 
      {
        $aLanguages = $_POST['formLanguages'];        
        if(!isset($aLanguages)) 
        {
            echo("<p>You didn't select any language!</p>\n");
        } 
        else 
        {
            $nLanguages = count($aLanguages);
            echo("<p>You selected $nLanguages languages: ");
            echo "<br/>";
            for($i=0; $i < $nLanguages; $i++)
            {
                echo($aLanguages[$i] . " ");
                echo "<br/>";
            }
            echo("</p>");
        }
      }
    ?>
   <form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
     <H2> Submit details:</h2>
     <label for='formLanguages[]'><h4>Select the Languages in which you are experienced:</h4></label><br>
     <select multiple="multiple" name="formLanguages[]">
        <option value="C">C Language</option>
        <option value="C++">C++ Language</option>
        <option value="C#">C#.NET Language</option>
        <option value="VB">VB.NET Language</option>
        <option value="JAVA">Java Language</option>
        <option value="PHP">PHP Language</option>
        <option value="PYTHON">PYTHON Language</option>
     </select><br><br><br>
     <input type="submit" name="formSubmit" value="Submit" >
   </form>
  </body>
</html>

Output of above code is:

Like us on Facebook