Click to See Complete Forum and Search --> : mysql + checkboxes


jrthor2
04-13-2008, 05:00 PM
I have a for that I have checboxes on and need to do a select from my table where the id equals any of the checboxes that were checked. My form code looks like this:

<input type="checkbox" name="ministries[]" id="<?=$committee;?>" value="<?=$catg_id?>" />

Now, in my results page, I want to have a sql call that used the checked values in the query. I have this, but it's not working

$sql = "SELECT id, committee, chairperson, email, description from committees where id in($ministries) order by committee asc";

I'm sure it's because the checkboxes are an array, but I'm not sure how to do this.

Thanks!

nonamepub
04-13-2008, 09:49 PM
I'm assuming the form data is being passed to another page (or to itself... point is, you're having the user hit submit)

On your processing page:

$value = $_POST['ministries'];

for ($i=0; $i < count ($value); $i+=1) {

$sql = "SELECT id, committee, chairperson, email, description from committees where id = '" . $value[$i] . "' order by committee asc";
ETC...
}


As for the parsing and executing, someone else may need to give you a hand - I'm an Oracle guy and I origionally thought this was for oracle... oops.

If you'd like to use boolean algebra in the select statement, you could first create a string for $values such as

for ($i=0; $i < count ($value); $i+=1) {
$whereStmt = 'id= \'' . $value[$i] . '\' '
}

And then stick that in right after the WHERE in your query. I hope this helps!

jrthor2
04-14-2008, 09:02 AM
I actually am using this, which seems to work as well:


$sql = "SELECT id, committee, chairperson, email, description from committees where id in(";
foreach ($ministries as $ministry) {
$values .= $ministry . ",";
}
$sql .= substr($values,0,-1);
$sql .= ") order by committee asc";

Thanks.

celebhir
04-15-2008, 03:16 AM
Hi jrthor2

How about using the implode() method? It's pretty neat ...
Once your page has posted use the following:


$values = $_POST['ministries'];
$sql = "select ID from myTable where ID in(" . implode(",", $values) . ");";


Hope that helps you out - it looks shorter and easier to read.

C

jrthor2
04-15-2008, 08:31 PM
I can't have a comma after the last item in the sql statement though. The in clause has to be like in (1,2,3). Will implode still work?

Thanks

jrthor2
04-16-2008, 08:00 AM
I tried the implode and it works good, thanks for the suggestion.

celebhir
04-16-2008, 04:52 PM
yip. it works just fine hey.
remember it's counterpart ... explode()
also handy for reverse engineering that ;)