PHP Tutorial: How to create Forms?

Now, we are finally upto doing some cool stuff with PHP and using its real power of creating forms and making HTML pages dynamic.

It is hoped that you know some HTML and can create static pages.

First, we create a simple HTML form as follows:

<html>

<head>

<head>

<body>

<form>

Name:

<input type=”text”name=”name”/>

<br>

Age:

<input type=”text” name=”age”/>

</form>

</body>

</html>

 

The output of the above form that does nothing is:

 

 

Name:

 

Age:

 


It is a pure HTML and in order to make it do something with the data that the user enters, we need a language like PHP that works upon this data and accomplishes something. Therefore, we add “action”, “method” and “submit” to this form as follows:

 

<html>

<head>

<head>

<body>

<form action=”perform.php” method=”post”>

Name:

<input type=”text”name=”name”/>

<br>

Age:

<input type=”text” name=”age”/>

<input type=”submit” />

</form>

</body>

</html>


The form now becomes:


Name:

 

Age:

 

Now, the code for perform.php is that does something like printing or doing some operation on the data recieved:

perform.php

<html><body>
<?php
$name = $_POST['name'];
$age = $_POST['age'];

echo “Your name is $name and age is $age”;

?> 
</body>
</html> 


Notice what has happened here. Post method in the earlier php code and action “perform.php” tells that the data in the form entered by the user has to be sent to perform.php where it can collect each form element data using $_POST.

Note: aciton is always the name of the file where the data should be directed when the form is submitted and the file (PHP file) that would do some processing on this data.

Therefore, if the user has entered name John and age 30 in the earlier form. The output of perform.php that would automatically come when the user presses the submit button in the earlier form would be “Your name is John and age is 30”.

I would not talk about 2 kinds of methods: GET and POST.

Comments on this entry are closed.

css.php