How to Retrieve Data from an HTML form Using PHP


How to Retrieve Data from an HTML form Using PHP

Let's say we're making an HTML form, such as the one shown below.

How do we now take the information that this person entered and do something useful with it, such as create a confirmation page or put it into a database for storage so that we can keep a list of all the people entering into this form?

And the answer is, we can do this using PHP.

Using PHP, we can extract the information that is input into a form and either post it on a web page, such as create a confirmation page with the data that the user has entered or store it in a database. In this article, we focus on extracting the information and displaying it on a web page.

To begin, let's examine what must be on the HTML page containing the web form which you see above:

How to retrieve data from a HTML web form using PHP

What that first line does containing the form tag with the action attribute is send the form to the PHP file, which in this case is contactinfo.php. This is a PHP file that you'll have a create that is programmed to extract the data out of this HTML form and output the data to the user's screen so he/she can have a confirmation of all the information that was entered. The method Post means we're going to be use the post superglobal array to extract information from the HTML forms.

Now that we know how we create the HTML page, let's go over how to create the PHP file.

PHP File


PHP file to retrieve data from a HTML web form using PHP

All of the code above the PHP script is standard HTML.

What we'll focus on now is the block of PHP code in this file.

In the first half of the block of PHP code, we are retrieving the data from the HTML web code. In this block of code, we create PHP variables (all beginning with $) and appropriately name them and set them equal to $_Post['name in HTML form']. So in the HTML form when we were asking for the user's first name, the name in the HTML form is FirstName. Therefore, $firstname= $_POST['FirstName']; since FirstName was the name attribute of that HTML form label in the HTML code. This is how we retrieve all the data from the HTML form.

Now we want to display this data so that the user can see what information he entered in the confirmation page. For this, we use the echo command. We print the label name, for example, First Name: ', then we add the concatenation operator, a period (.), in order to append data together, and then use the PHP variable which represents each of the form fields extracted from the HTML form.

We use another concenation operator to add Br tag- Line break which gives a line break in each of the fields. This is so that each of the fields aren't all on one line.

HTML Comment Box is loading comments...