Current course:

PHP - getting <form> data

When you submit a form, you need to be able to process the data.

This is usually done using another language like PHP or ASP. Often the form data is inserted into a database, emailed, or used to alter the contents of the page.

In this case, we're going to cover how to utilize data submitted from a <form> with simple PHP.

1) First, create a file with .php as it's extention (example formStuff.php). A PHP document is almost identical to an HTML document - the only noticable difference is that a PHP file allows us to use PHP code. It still lets us write HTML code, just like an HTML document, and we don't even NEED to use any PHP on the page - but it lets us if we decide to.

2) Then, in the body, we create a form:

<form action="" method="post">
      <input type="text" name="first" value=""><br />
      <input type="text" name="last" value=""><br />
      <input type="submit" value="submit" name="submit">

When the form is submitted, it will send the data to whatever the "action" attribute is set to. In this case, it's blank, so the form will just send the data to the current page we're on.

It's "method" is set to "post", meaning the data will be sent in the background (not in the URL).

"Get" lets you bookmark the page whereas if you use "Post" it will not have the variables in the URL when you bookmark it.

When you submit your form, you'll notice nothing happens. That's because we haven't told our page what to do with the data.

3) To retrieve the data, we use PHP which we designate with a <? to tell our file we're starting PHP code, and a ?> to tell our file we're ending our PHP code. Think of these like the <script> and </script> tags you use to denote the start and end of your javascript code.

      echo $_POST['first'];

Within the start and end PHP "tags", we use an "echo" which writes something to the page. If you wrote:    echo "hello world";    it would just put "hello world" on the page (without quotes).

In this case, though, we use $_POST['first'] which tells our PHP that we want to write the value of the form element named "first" to the page. If you sent your form data with "get" instead of "post", you can just do the same thing, but replace $_POST with $_GET.

A shorthand way of writing the same thing is:

<?=$_POST['first'] ?>

4) To utilize data from the form, just include it throughout your page:

Hello, <?=$_POST['first']?> <?=$_POST['last']?>, how are you today?