Manipulating Data Submitted via a Form (Part I)

Accepting input from the user

At some point during an aspiring web developer's quest for knowledge, he or she is bound to ask the question, "Alright, I can write a script that does some random stuff... Now how do I do something cool enough to trick all of my nerdy friends into falling madly in love with me?"

The answer to this question can be found in accepting input from the user.

After a developer has mastered some of the basics of PHP, like the if statement, accessing variables, modifying variables, and outputting variables or strings, the next logical step is to begin experimenting with data. And what better way is there to get data than to ask someone else for it?

We can facilitate this concept of 'accepting input from the user' by using an HTML form. When a user submits a form, the web server will take the data submitted and put it in a PHP variable called $_POST. Through this variable, we can access any of the form elements submitted to a given script.

Creating the form

Before we begin writing HTML for our form, we must first ask ourselves what our purpose is, or more specifically, what information we want to ask the user for.

In the example that I'll be presenting, I will be creating a place where my users can leave comments about my site. This means that I could ask the user for the following data:

Take a few moments, come up with a purpose for your form, list the information you want to ask the user for, and then write it using HTML.

Here is what I came up with for my comment form (comment_form.php):

Please take note of the first line of the form.

In the above line of HTML markup, we specify that the data submitted in the form should be sent to comment_form.php (the file we are working with right now) via the method post. This means that the data submitted in the form will be available for use in our script via the $_POST variable after a user has pressed the submit button.

Also notice that every input field in the form has a name. For example, look at the following line of code.

$_POST

The variable $_POST is actually an array of variables. For those inexperienced with arrays, $_POST can be considered a variable that holds many other variables. To access the data submitted in any element of the form, we can use the following:

So, to get the subject of the comment submitted, we could use the following variable:

If we were to use the echo function on this variable after the form had been submitted, it would output the string of text stored in the variable.