PHP: A simple form using $_POST

This entry is part 37 of 54 in the series PHP Tutorial

After you have installed the WAMP server into your PC, we are ready to work on a simple form.

I have tried  a few online php code editors and they are not suitable for creating forms and so you can try the code below on your own PC.

<html>
<body>

<form action="" method="post">
    Name: <input type="text" name="name"><br>
    E-mail: <input type="text" name="email"><br>
    <input type="submit">
</form>

</body>
</html>
<html>
<body>

<?php
$your_name = $_POST["name"];
$your_email = $_POST["email"];
echo "Welcome " . $your_name."<br>";
echo "Your Email is " . $your_email; ?>

</body>
</html>

You can try the form here.

Notice how the name and email are passed into the PHP code using

$_POST[“name”]
$_POST[“email”]

The $_POST is a superglobal variable.  They are global variables defined in PHP and they are accessible anywhere in the code.

As we have put the php code in the same form as the HTML form, we might see warnings related to the 2 lines below.

$your_name = $_POST["name"];
$your_email = $_POST["email"];

We can put @ in $_POST as in

$your_name = @$_POST["name"];
$your_email = @$_POST["email"];

This is to prevent the warning message as we have put the name variable in the input form into the php code.  You can also use it without the @ but a warning message could be rendered in the page.

Usually we would have separated the HTML form with the php code by putting the php script in a separate file as shown in the next example.

 

Series Navigation<< PHP: Apache Web & PHP server
PHP: A two-step process to display the form >>

Leave a comment

Leave a Reply