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

June 7, 2006

Better array pushing

In any language, you’ll often find yourself working with arrays. PHP offers a couple methods for adding items to them. Say you have an array:

$arrayvals = array("elton", "sam");

and you want to add the value, “shaun” to it. You can either do:

$arrayvals[] = "shaun";

or you can do:

array_push($arrayvals, "shaun");

So which is better, or does it even matter? The answer is the first one, $arrayvals[]=”shaun”;, because according to the php manual, there is no overhead of calling a function with this method. A minor difference, but when writing web apps, every line you write is potentially called millions of times per second so you don’t want to be wasting cycles for no reason. Is there a point to array_push then? Remember that array_push allows adding multiple values at once so it’s easier to do:

array_push($arrayvals, "shaun", "corey", "chris");
Filed under: PHP, Arrays — Kevin @ 2:32 am

Home
© 2006 NoviceCoder | All rights reserved.