novicecoder.com

July 20, 2006

Implode checkbox group arrays into query strings

In going from an html form to php code and finally to a sql query there are a lot of steps that could get messy, but fortunately php has a simple way to do this all. Let’s say I have some checkbox options on my html form for a user to select the sports they like.

<input type="checkbox" name="sports[]" value="baseball">
<input type="checkbox" name="sports[]" value="basketball">
<input type="checkbox" name="sports[]" value="football">
<input type="checkbox" name="sports[]" value="hockey">

Note how the checkboxes are grouped by giving them the same name with the index ([]) suffix. This makes it so that an array containing the checked values is returned. The next step is to use the php function implode. This function takes an array and creates a delimited list of the array items connected by whatever glue string you want. The simple example is to generate a comma delimited list like “basketball, baseball, football, hockey”.

$csv = implode(",", $_POST['sports']);

In this example we want to build a query string.

$query = "SELECT * FROM sportstable WHERE
         sport='" . implode("' OR sport='",$_POST['sports']) . "'";

This would create the string, “SELECT * FROM sportstable WHERE sport=’basketball’ OR sport=’baseball’ OR sport=’football’”, with the items that were checked by the user. Of course you’ll want to validate the input first (check that the array count is greater than zero, sql injection, etc.) but user input validation is a whole post of its own.

Filed under: PHP, Site Info, Strings, Arrays — Kevin @ 5:42 am

Home
© 2006 NoviceCoder | All rights reserved.