the Future of the Web
  • Home
  • Hire Us
  • Articles
  • About
  • Contact
  • Use Arrays in HTML Form Variables

    Nov 4 2008

    When you're dealing with processing forms, a lot of the time you have a one-to-one mapping of form fields and database columns, with perhaps an extra submit button or some fields that need special processing (eg. passwords).

    Although many frameworks like CodeIgniter make this easier, you can still easily come up with code like this:

    $this->db->insert('accounts', array(
        'first_name' => $this->input->post('first_name'),
        'last_name' => $this->input->post('last_name'),
        'email' => $this->input->post('email'),
        'address1' => $this->input->post('address1'),
        'address2' => $this->input->post('address2'),
        'city' => $this->input->post('city'),
        'state' => $this->input->post('state'),
        'zip' => $this->input->post('zip'),
        'phone' => $this->input->post('phone'),
        'fax' => $this->input->post('fax')
    ));
    

    See all that repetition? Whenever you see a group of lines that look almost the same, you know there is probably an opportunity to clean things up. Well luckily, there's a really neat one.

    You can create arrays in form fields using square brackets. That means you can name fields like account[first_name] and account[last_name] and in most server-side languages, you will end up with an 'account' array.

    In HTML, PHP and CodeIgniter, that might look something like this:

    <input type="text" name="account[first_name]"/>
    <input type="text" name="account[last_name]"/>
    <!-- etc... -->
    <input type="text" name="account[fax]"/>
    <input type="submit" name="submit"/> <!-- note the lack of 'account' -->
    
    // meanwhile, on the server...
    $account = $this->input->post('account');
    
    // VERY IMPORTANT: unset any fields that shouldn't be edited
    unset($account['id']);
    
    $this->db->insert('accounts', $account);
    

    See? Much cleaner. Yes, you do open a slight security hole potential, so be very careful when doing this on tables that have security implications, ie. user data. If you have an 'admin' column on your 'users' table, someone could maliciously add <input type="hidden" name="users[admin]" value="1"/> to your form using Firebug and grant themselves administration access. You can solve this by adding something like unset($user['admin']); to the incoming data. If you wanted to be really safe, you could have an array of the keys you want to allow and filter against that using something like PHP's array_intersect_key with array_flip:

    $user = $this->input->post('user');
    
    // only allow keys in $user to match the values in $columns
    $columns = array('first_name', 'last_name', /* etc.. */ );
    $user = array_intersect_key($user, array_flip($columns)));
    

    You can even do this with checkboxes and multiple select boxes, and alternatively leave out the key in the array to create a regular array (ie. not associative) of values:

    <label><input type="checkbox" name="choice[]" value="1"/> 1</label>
    <label><input type="checkbox" name="choice[]" value="2"/> 2</label>
    <!-- etc... -->
    
    // meanwhile, on the server...
    $choice = $this->input->post('choice');
    
    print_r($choice); // Array ( [0] => 1 [1] => 2 )
    

    This "trick" can really clean your code up. I used it recently to drastically simplify a form that had a shipping address and billing address. If the user checked a box saying "My shipping and billing are the same", I was able to simply do something like this:

    $shipping = $_POST['shipping'];
    $shipping_billing_same = $_POST['shipping_billing_same'];
    
    if ($shipping_billing_same) {
        $billing = $shipping;
    } else {
        $billing = $_POST['billing'];
    }
    

    Much nicer than that 24 form fields that were hard-coded previously.

    I've given examples here in PHP and CodeIgniter. Does anyone else want to give examples in other server-side languages and frameworks?

    Tags: html php codeigniter
    View 13 Comments | Add a comment
  • Comments

    1. Peter Baumgartner at 7:41am on November 4, 2008

    f = ArticleForm(request.POST)
    if f.is_valid():
        new_article = f.save()

    This is an area where Django shines: Django Model Forms

    2. Susie at 11:25am on November 4, 2008

    For anyone starting out with PHP, its worth mentioning that its also important to do some checking / stripping of malicious code to the variables input by a user form before you put them in your database.

    3. Frank at 5:30pm on November 4, 2008

    Susie,

    The great thing about CodeIgniter is that it offers the ability to automatically strip any unsafe input from forms.

    4. Thai Bui at 6:12am on November 16, 2008

    It's nice, I've used it with Zend Framework, but it make another issue, you face with it when trying to validate form using Javascript, can't access to a form named like "account[address] by document.form_name.account[address].value.
    Do you have any ideal?!?

    5. Jesse Skinner at 6:32am on November 16, 2008

    @Thai - I'm not sure, but I'd suppose you'd do it like:

    document.form_name["account[address]"].value

    Of course you could just add an ID and use

    document.getElementById('account_address');

    6. Thai Bui at 6:39am on November 16, 2008

    yup, I haven't try it either, I just remember another issue is when you submit a form using GET method, at that time your url is abc.com?account=Array, and then in PHP you received it

    $account = $_GET['account']; // $account = 'Array';

    feeling confuse? ^_^

    7. Dave H at 10:37pm on December 1, 2008

    I wrote a function that gets and cleans specific $_POST keys, so you can be sure you're only inserting what you want into the database.

    Eg something like
    $data = cleanRequest(array('id_i', 'name', 'email'));
    $db->insert('people', $data);

    I also give all user input that I want validated for the DB a _type suffix, eg _i for integer as above.  That way I don't have to worry about bad user data.

    Using document.form_name["account[address]"].value in JavaScript seems to work fine.

    8. Roshan Bhattarai at 8:11pm on December 13, 2008

    yes much cleaner but you can use this cleaner approach without using array in form as well ... here is the snippet of what I do in my projects.

    the model function will be called like this
    $this->Modelproducts->insertProcuct($_POST);

    and here is modal function

    function insertProduct($data)
    {
      unset($data['submit']); unset($data['id']);
      $this->db->insert('product', $data);
    }

    9. john at 9:46am on January 5, 2009

    Nice article, I also give all user input that I want validated for the DB a _type suffix, eg _i for integer as above.  That way I don't have to worry about bad user data.
    http://www.cyberdesignz.com/

    10. Thorpe Obazee at 6:43am on March 3, 2009

    Doesn't this approach just make it longer to code? I think the first approach is quite clean and will stick to it.

    Still, nice approach.

    11. Stacy at 1:14pm on April 20, 2009

    great spider! I'm biulding  asite for a small company. They need spiders to crawl certain sites. Considering I never did anythin with spiders. This takes a big load of my shoulders.... thank you!!!

    My guestion is, how to i get all of the...


    Use Arrays in HTML Form Variables....
    Array ( [0] => Array ( [0] =>

    not to show?? thank you

    12. Rukesh at 7:45pm on May 14, 2009

    This tutorial is really great!!
    I want to learn from this website more

    13. ZK@Web Marketing Blog at 1:28pm on June 29, 2009

    Python is for developpers not endusers. A developper does not want an all-in-one install package that only allows you to install a package in the one true fashion. That’s why I like tarballs, because I can install it where and how I want without disturbing any other parts of my system that I don’t want to disturb.

    Add a Comment

    Note: HTML tags and entities will be converted so that they are displayed as you type them. This means if you type in <em>, people will see <em>, and if you type &lt;em&gt;, people will see &lt;em&gt;.

  • Request a Quote

  • Jesse Skinner

    Jesse Skinner
    • Hire Me
    • About Me
    • Email Me
    • RSS Feed RSS Icon
    • @JesseSkinner
  • Recent Articles

    • jQuery Live Events
    • I need web developers
    • buttons need type="submit" to submit in IE
    • Win $200 in a Web Dev Writing Contest
    • Use Arrays in HTML Form Variables
    • 5 Reasons Freelancers Can Succeed in a Shrinking Economy
    • Keeping a Live Eye on Logs
    • Using PHP's empty() Instead of isset() and count()
    • Testing Web Pages with Lynx
    • Stop CSS Background Flickering in Internet Explorer 6
    • See All...
  • Categories

    • javascript (39)
    • links (21)
    • about (19)
    • web (14)
    • html (12)
    • server (11)
    • css (8)
    • browsers (8)
    • carnival (7)
    • work (6)
    • design (4)
    • seo (4)
    • ads (4)
    • standards (4)
    • events (4)
  • Older Articles

    • February 2009
    • January 2009
    • December 2008
    • November 2008
    • October 2008
    • July 2008
    • June 2008
    • May 2008
    • April 2008
    • February 2008
    • January 2008
    • December 2007
    • November 2007
    • September 2007
    • August 2007
    • July 2007
    • June 2007
    • May 2007
    • April 2007
    • March 2007
    • February 2007
    • January 2007
    • December 2006
    • November 2006
    • October 2006
    • September 2006
    • August 2006
    • July 2006
    • June 2006
    • May 2006
    • April 2006
    • March 2006
    • February 2006
    • January 2006
    • December 2005
    • November 2005
    • October 2005
    • September 2005
    • August 2005
    • April 2005
    • See All...
Copyright © 2009 The Future of the Web