Thursday, August 16, 2012

PHP - Form elements

In this article we will see how to create form in PHP and send data to next PHP page. Like other languages you need to specify the methods with which your data will be sent - "GET" and "POST". If you've used the POST method, you can find that data in the $_POST array similarly if you've used the GET method, you use the $_GET array. These array are "super global" arrays, which means that they're available to you without having to use the global keyword. Also, there is a $_REQUEST array which holds data from both $_GET and $_POST array.

We will create a form which contain various form elements like text box, password, radio button, select dropdown, text area and check box.


formPage.php

<html>
<head>
  <title> PHP - Form page </title>
</head>
<body>
  <form method="post" action="submitPage.php">
    <table border="1" width="100%">
    <tr>
      <td>User name : </td>
      <td><input type="text" name="userName"></td>
    </tr>
    <tr>
      <td>Password : </td>
      <td><input type="password" name="password"></td>
    </tr>
    <tr>
      <td>Gender : </td>
    <td>
      <input type="radio" name="gender" value="M"> Male
      <input type="radio" name="gender" value="F"> Female
    </td>
    </tr>
    <tr>
      <td>City : </td>
    <td>

      <select name="city">
        <option value="Chennai">Chennai</option>
        <option value="Delhi">Delhi</option>
        <option value="Kolkata">Kolkata</option>
        <option value="Mumbai">Mumbai</option>                                                     
      </select>
    </td>
    </tr>
    <tr>
      <td>About you : </td>
      <td><textarea name="aboutYou"></textarea></td>
    </tr>
    <tr>
      <td>Community : </td>
    <td>
      <input type="checkbox" name="community[]"  value="c">C
      <input type="checkbox" name="community[]" value="C++">C++
      <input type="checkbox" name="community[]" value="Java">Java
      <input type="checkbox" name="community[]" value=".Net">.Net
    </td>
    </tr>
    <tr>
      <td colspan="2" align="center"><input type="submit" value="Submit Form"/></td>
    </tr>
    </table>  
  </form>
</body>
</html>

submitPage.php

<html>
<head>
<title> PHP - Submit page </title>
</head>
<body>
  <?php
    echo "User name : ".$_REQUEST["userName"]."<br/>";
    echo "Password : ".$_REQUEST["password"]."<br/>";
    echo "Gender : ".$_REQUEST["gender"]."<br/>";
    echo "City : ".$_REQUEST["city"]."<br/>";
    echo "About you : ".$_REQUEST["aboutYou"]."<br/>";

    echo "Community : ";
    if(!empty($_REQUEST["community"]))
    {
      $community = $_REQUEST["community"];
      $count = count($community);
      for($i=0; $i < $count; $i++)
      {
        echo($community[$i]." ");
      }
    }
    else
    {
      echo("You didn't selected any Community.");
    }
  ?>
</body>
</html>

Output