Many applications in php language need a form, for example
guestbook, forum, form mailer...
A form is a module that allows to insert data that
will be elaborated by the script.
So, I decided to treat this important argument. In this
article I try to explain to you how to build a form and
how to build the php code to elaborate the data coming from
the form. Near the rows of code I will insert a number to
comment the code.
Now I build a form containing the fields 'name','surname'
and 'age':
1: <form name="myform"
action="elaborate.php" method="post">
2: Name:<input type="text"
name="name" size="30"><br>
3: Surname:<input type="text"
name="surname" size="30"><br>
4: Age:<input type="text"
name="age" size="5"><br>
5: <input type="submit" value="Go">
6: </form>
Comment of the code:
At the row 1 I defined the name of the
form by the attribute name,
by the attribute action we want that the data coming
from the form must be elaborated by a file named elaborate.php
while by the attribute method we estabilish how
the data are sent to the file elaborate.php.
From row 2 to row 4 I insert the
text-fields
to put name,surname and age.
At row 5 I insert the button to send the
data to the file defined initially in the attribute
action that is to say the file elaborate.php
At row 6 I close the form.
We can save the code in a file called for example form.html.
In the next page we will see how to build the page
elaborate.php that will elaborate the data coming
from the form.
Now we see how to build the file elaborate.php that will
elaborate the data coming from the form. For the first time
now we will see php code and for this reason the page must
have .php extension.
Php code must be contained between the tag <? ?> or
between the tag <?php ?>. Only the code between these
tags is a php code.
1: <?
2: $name=$_POST['name'];
3: $surname=$_POST['surname'];
4: $age = $_POST['age'];
5: echo "Name: ".$name."<br>";
6: echo "Surname: ".$surname."<br>";
7: echo "Age: ".$age."<br>";
8: ?>
Comment of the code:
At rows 2,3 and 4 by the function $_POST
I store the fields 'name','surname' and 'age', coming from
the form,in the variables $name, $surname, $age (in php
the variables must always
start with the simbol $).
Then at row 5,6 and 7 we print on screen
the variables $name, $surname and $age by the function echo.
The point has the meaning of an append, that is to say it
links more words together.
For example at row 5, it is printed on
screen before the string Name: then the variable $nome then
<br> (that is to say 'new line').
Note: Each instruction in php language
must end with a ;