Better Form Processing


This is a much condensed version of the original post.

Usually, processing form data means getting either POST or GET data from a form, and trying to figure out, in code, what you have, and then do something with it.  This can be easy or complicated, depending on how much is being passed in.  Email address only? Easy.  Checkboxes, optional fields, and so on, all together?  Pain.  Often, a lot of form processing is done with stacks of “if” statements.  This sucks.  Here is a better way:

From now on, I want you to name all of your “real” form elements (ones that have data that could change, so not buttons) using the name you would have given then, plus an array name, that they will all share.


<input type="text" name="username" id="username" />


<input type="text" name="formdata[username]" id="username" />

Why?  Instead of having one array ($_POST), you’ll now have two ($_POST and ‘formdata’, within $_POST).  Your buttons and other “static” form elements will still live in $_POST, but everything containing data that needs handling will be in the ‘formdata’ array, which you can access as $_POST[formdata].

Why does this rock?  I find I have to go through all of the data in a form, even if I know what and how much is coming in, and that the amount wont change.  For example, it’s a good idea to clean all user input.  Since users can change any form value, this needs handled.  Why bother with a ton of ‘if’ statements when we can just iterate through the ‘formdata’ array?

  foreach ($_POST['formdata'] as $key => $value)
    $_POST['formdata'][$key] = makesafe($value);

Cautionary note: this definitely seems ideal for updating data in a database and saving time, doesn’t it?  Maybe something like (let’s assume “$user_id” is the current user’s account, and we determined that earlier somehow) :

  foreach ($_POST['formdata'] as $key => $value)
    mysql_query("UPDATE info_table SET $key = '$value' WHERE index = $user_id");

This is a bad thing.  Why?  SQL injection.  At the very least, clean all input, including the field names, if you think something like the above statement is a good idea.  If you don’t, don’t say I didn’t warn you if you get owned.