novicecoder.com

August 20, 2006

Find and replace in SQL tables

Pretty obvious, but I had to look it up so I figured I should save it here. Say I misspelled “people” as “peeple” and I wanted to fix them all in my database. Just do:

UPDATE table SET field=REPLACE(field, ‘peeple‘, ‘people‘ );
Filed under: Site Info — Kevin @ 6:17 am

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 2, 2006

Purpose

This is my log for random coding things that make life easier. Most things won’t be too technically advanced, but rather buried features that might not be obvious. They’re typically things I’ve learned by writing some long method and having someone else come along and ask why I didn’t just do it this other simpler way.

Filed under: Site Info — Kevin @ 7:00 pm

Home
© 2006 NoviceCoder | All rights reserved.