Hudzilla.org - the homepage of Paul Hudson
Contents > HTML Forms > Handling data Wish List | Report Bug | About Me ]

7.4.5     Handling our form

This is NOT the latest copy of this book; click here for the latest version.

You now know enough to be able to program a script to handle the advanced form presented previously, so let's break it down.

Firstly, you should note that our variables will be coming in using the GET method. In the real world you would use POST because it is possible that users will submit large quantities of data in the "Life story" field, however using GET here lets you see how it all works. Because we're using the GET method, we should be reading our variables from $_GET.

The first two fields sent are Name and Password, which will both contain string data. Remember that the password HTML form element transmits its data as plain text, which means that both Name and Password can be handled the same way. As they are coming in via HTTP GET, they values entered by our visitors will be in $_GET['Name'] and $_GET['Password'] - note that the cases have been preserved from the form exactly, and that, as per usual, PHP considers $_GET['name'] to be different from $_GET['Name'].

Moving on there is the select list box Age, which will return a string value - either "Under 16", "16-30", "31-50", or "51-80". >From the PHP point of view, this is no different to handling input from a text box other than we can, to a certain extent, have an idea about what the values will be. That is, under normal circumstances we will always know what the values will be, as our users have to pick one option from a list we present. However, it takes only a little knowledge to "hack" the page so that users can input what they like - just remember the golden rule, "Never trust user input".

The Story text area element submits data in the same way as a normal text box does, with the difference that it can contain new line characters \n. The chances are that you want to convert these new line characters into HTML line breaks (the <BR /> element), and you can use this simple str_replace() example to do just that:

$_GET['Story'] = str_replace("\n", "<BR />", $_GET['Story']);

Next we get to our radio buttons, FaveSport. As radio buttons can only submit one value, this one value will be available as a normal variable in $_GET['FaveSport']. This is in contrast to the check box form elements that follow - they have the name Languages[], which will make PHP convert them into a single array of values, available in $_GET['Languages'].

That is the entire form covered - we can put the whole script together now using the above information, plus the other techniques we've covered in previous chapters. Here is a script I wrote to parse the form - you should copy mine yourself, then try rewriting it using some of the other functions.

<?php
    $_GET
['Languages'] = implode(', ', $_GET['Languages']);
    
$_GET['Story'] = str_replace("\n", "<BR />", $_GET['Story']);

    print
"Your name: {$_GET['Name']}<BR />";
    print
"Your password: {$_GET['Password']}<BR />";
    print
"Your age: {$_GET['Age']}<BR /><BR />";
    print
"Your life story:<BR />{$_GET['Story']}<BR /><BR />";
    print
"Your favourite sport: {$_GET['FaveSport']}<BR />";
    print
"Languages you chose: {$_GET['Languages']}<BR />";
?>

As you can see, the entire script to handle the HTML form we created is just eight lines long, of which six are just print statements reading from the $_GET array. The first two lines aren't anything special, either - line one converts the Languages array created from the check boxes into one string using implode(), and line two converts the new line characters in the Story text area into HTML line breaks.

However, the script above contains an bug - what happens if our users don't check any boxes for languages? The answer is that browsers will not send any languages information, which means that $_GET['Languages'] will not be set, which in turn means that the first line in the script will cause an error! The solution is fairly simple, though - use if (isset($_GET['Languages'])) to check whether there is a value set: if there is, use implode() to make it a string, and if not, put a dummy text string in there like "You did not select any languages!"







<< 7.4.4 Data handling summary   7.5 Splitting forms across pages >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
alandakin@hotmail.com - 05 Dec 2008

I cannot get this to send (or print) the variables.

The someform.php only returns the names of the fields not te contents.

A PHP User - 05 Dec 2008

CheX,

you can modify your database on a different way. If it is MySQL, the see http://www.php.net/manual/en/ref.mysql.php

CheX - 05 Dec 2008

HI,
I'm making an online game, but one thing has fummed me. And you do not cover this aspect I'm looking for.
Drop down boxs.In my game I have 7 races, and I can't get the drop down box to hold information, like race stats, items etc.

this is the first few lines of my race code.
if($_POST['Race'] == '0')
{
$_Angel=$_POST['race'];
$_AngelS=$POST['strength'];
$_AngelSp=$_POST['speed'];
$_AngelInt=$_POST['intelect'];
$_AngelWis=$_POST['wisdom'];
$_AngelZes=$_POST['zest'];
$_AngelGo=$_POST['gold'];

...
I've made the entire script with no errors.
But it will not send the information desired to the database!
Anyone have any bright ideas?

CheX - 05 Dec 2008

HI,
I'm making an online game, but one thing has fummed me. And you do not cover this aspect I'm looking for.
Drop down boxs.In my game I have 7 races, and I can't get the drop down box to hold information, like race stats, items etc.

this is the first few lines of my race code.
if($_POST['Race'] == '0')
{
$_Angel=$_POST['race'];
$_AngelS=$POST['strength'];
$_AngelSp=$_POST['speed'];
$_AngelInt=$_POST['intelect'];
$_AngelWis=$_POST['wisdom'];
$_AngelZes=$_POST['zest'];
$_AngelGo=$_POST['gold'];

...
I've made the entire script with no errors.
But it will not send the information desired to the database!
Anyone have any bright ideas?

A PHP User - 05 Dec 2008

Cut and paste this is what I have

", $_POST['Story']); print "Your name: {$_POST['Name']}
"; print "Your password: {$_POST['Password']}
"; print "Your age: {$_POST['Age']}

"; print "Your life story:
{$_POST['Story']}

"; print "Your favourite sport: {$_POST['FaveSport']}
"; if (isset($_POST['Languages'])) { print "Languages you chose: {$_POST['Languages']}
"; } else { print "You did not select any languages!" ; } ?>

Could just be missing something obvious but cant seem to find it

Thanks

A PHP User - 05 Dec 2008

Could not get the script to run .
Just got a reprint of the stuff in quotes with all the gets and posts.
By the way it seems as if the date does not change on this page or it changes everyday and gives everybody the current date
Thanks

Mike

SNApY - 05 Dec 2008

For Keith:
Make a HTML form page (form.html) and someform.php. You probably made the form in PHP (I did the same).
Here's php code without the bug:
<?php
$_POST['Languages'] = implode(', ', $_POST['Languages']);
$_POST['Story'] = str_replace("\n", "<BR />", $_POST['Story']);

print "Your name: {$_POST['Name']}<BR />";
print "Your password: {$_POST['Password']}<BR />";
print "Your age: {$_POST['Age']}<BR /><BR />";
print "Your life story:<BR />{$_POST['Story']}<BR /><BR />";
print "Your favourite sport: {$_POST['FaveSport']}<BR />";
if (isset($_POST['Languages'])) {
print "Languages you chose: {$_POST['Languages']}<BR />";
} else {
print "You did not select any languages!" ;
}
?>

A PHP User - 05 Dec 2008

no comments

Mark - 05 Dec 2008

>>After 2 or 3 hours messing about I found that you cannot >>check for blank fields from a form with isset().

With the exception of a non-pressed button control and an unchecked checkbox, all fields are returned and therefore the variables are initialized on submit. So isset() will always yield true.

How about testing for empty()? Except be careful, empty("0")==false

Keith - 05 Dec 2008

My scripting does not seem to parse anything. What is printed as my results is actually what is in quotes.
Why?

A PHP User - 05 Dec 2008

After 2 or 3 hours messing about I found that you cannot check for blank fields from a form with isset(). Haven't a clue why it doesn't work, but it doesn't (at least not with POST). Again I don't know why, but the empty() function does work.

A PHP User - 05 Dec 2008

The difference with nl2br() is that it does not replace the "\n" entity with a "<br/>" entity. It inserts a "<br/>" in front of each "\n". If you don't want both, you're better off with the str_replace code the author used.

Dirk - 05 Dec 2008

instead of this

$_GET['Story'] = str_replace("\n", "<BR />", $_GET['Story']);

you should use "nl2br()" that handles the the newlines "\r\n" and the combinations of it the right way,
so example will read:

$_GET['Story'] = nl2br($_GET['Story']);

easy, hm?



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is two plus three?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow