Greg's Blog

helping me remember what I figure out

The Problem With Multiple Selects and Php

| Comments

Forms are the primary method for users to interact with web applications and though there are a number of pitfalls associated with user interactions and forms, I want to specifically take a closer look at the way PHP behaves when dealing with a particular form element: the multiple select box. Listed below is a standard form and select input box

<form action=”some_html.html” method=”post” name=”frm_test” id=”frm_test” enctype=”application/x-www-form-urlencoded”>
<select name=”test_select” id=”test_select” multiple=”multiple”>
<option value=”1”>1</option>
<option value=”2”>2</option>
<option value=”3”>3</option>
<option value=”4”>4</option>
</select>
<input type=”Submit” name=”btn_submit” id=”btn_submit” value=”Submit” />
</form>

This is a pretty standard form with a normal multiple select box. The user can select one or more options and then click on the submit button and pass these values to the server for processing. If you were using PHP as your server side scripting language, submitting this form with more than one option selected would result in only one value being passed to the application or script that you are calling. Why? Well it turns out that multiple select values are actually passed in an array and PHP needs to understand it as such (I may be really oversimplifying this, but what the hey this really works). The first thing you’ll need to do is change the way you name your form variables for that type of form field, i.e. instead of using name=”test_select” you’ll need to refer to it as name=”test_select[]”. When this form field is submitted PHP will now know that the values are stored in an array. So here is the now amended form:

<form action=”some_html.html” method=”post” name=”frm_test” id=”frm_test” enctype=”application/x-www-form-urlencoded”>
<select name=”test_select[]” id=”test_select[]” multiple=”multiple”>
<option value=”1”>1</option>
<option value=”2”>2</option>
<option value=”3”>3</option>
<option value=”4”>4</option>
</select>
<input type=”Submit” name=”btn_submit” id=”btn_submit” value=”Submit” />
</form>

Now this style of annotation may cause one or two errors with your existing JavaScripts. So as a work around just change the attribute name to the new naming convention as JavaScript references the id attribute (if provided, else I think it uses name)