Thursday, 2 June 2011

Lesson 8 : PHP form handling

Retweet this button on every post blogger
Sending form data from one page to another for further processing in an quite simple task in PHP, By setting up only form input type name attribute we can extract them at the server side using PHP global array.
Some example global  array in PHP which we often use in form handling are :

$_POST[]
$_GET[]
$_SERVER[]
$_REQUEST[]
$_COOKIE[]

The global arrays are all associative arrays. This means the value is associated with a name that is the index key for the contents and, sensibly, describes what the value represents. For instance,$_SERVER["SCRIPT_NAME"] contains the URL path to the current page.

Sometimes you can also access the values of the array directly by variable name. This varialbe name is the same as the index key for the array. Thus, the variable name for $_SERVER["SCRIPT_NAME"] would be$SCRIPT_NAME. this can be achieve by extracting the array. 

I think this is enough for any beginner. lets look at the example.
page1.php
<html>
<head><title>PHP from handling.</title></head>
<body>
<form action = "page2.php" method="post">
<center>
<table>
<caption>General info</caption>
<tr>
<td>First Name</td><td><input  type="text" name="fname" /></td>
</tr>
<tr>
<td>Last Name</td><td><input  type="text" name="lname" /></td>
</tr>
<tr>
<td>Address</td><td><input  type="text" name="add" /></td>
</tr>
<tr><td>&nbsp;</td><td><input  type="submit" name="submit"  value="Go.."/></td></tr>

</table>
</center>
</form>
</body>
</html> 
                                                                    --Output--
page2.php
<html>
<head><title>PHP from handling.</title></head>
<body>
<center>
<table>
<caption>General info</caption>
<tr>
<td>First Name</td><td><?php echo $_POST['fname']; ?></td>
</tr>
<tr>
<td>Last Name</td><td><?php echo $_POST['lname']; ?></td>
</tr>
<tr>
<td>Address</td><td><?php echo $_POST['add']; ?></td>
</tr>
</table>
</center>
</body>
</html>   
                                       
                                                                   --Output--
 for sake of simplicity we also extract $_POST[] array as extract($_POST);, and simply use the form input names as POSTED variables in pag2.php.