RSS

POST Variables

Sun, Jan 17, 2010

PHP & MySql

When you create forms, you can either use the POST or GET method. In this chapter I’ll be explaining the POST method, in which the data is put into POST variables. POST variables are just like normal arrays which contain a certain amount of (sub-)variables. Once a form is submitted, for each form field one sub-variable will be created for the array POST, the name of the sub-variable (index) will be equal to the name of the field. The value of the sub-variable will be equal to the value of the form field ( what the user filled in or the default value otherwise, if set ). So let’s start with creating a form that uses this POST method.

Example:

... form fields ...

We simply put method=”POST” to the form tag, to make it use this method. The action here is set to some “handle_file.php”, could as well be set to any file or even the same file. It’s the file it will send the data ( using the POST method, in POST variables so ) to and go to when the form is submitted. Let’s add an example form field and submit button.

Example:

In this case, once the user submits the form by clicking on the submit button, the text filled in in the field ‘username’ ( the first input field with name=’username’ ), will be put into the variable $_POST[‘username']. The same goes for all input fields. All values of the input fields will be stored into a variable $_POST[‘field_name_here'] and sent to the action file. Let’s use this to greet the user when he fills in his username and submits it:

File: form.php

File: handle_file.php

<?php
if(!empty($_POST['username']))
    echo "Hi there ".$_POST['username']."!";
 ?>

What we basicly done here is check if the field username is not empty, as the value of it would be stored into $_POST[‘username'] once the form has been submitted. So we actually check 2 things by checking whether it’s not empty. We check if the form has been submitted at all, and we check whether the input field with the name username has not been left blank. Then we use the value of it ( the username the user filled in ) to greet the user with a simple greeting.
That’s it, if you have any further questions about this chapter ( POST variables ), feel free to ask.

Cheers,
Admin.