Jump to content


This topic is now archived and is closed to further replies.


PHP Checkboxes, dynamically change MySQL query

Recommended Posts

Hi all! Let's say I have the following ten checkboxes:

[code]<input name="checkbox_1" type="checkbox" value="1" />
  <input name="checkbox_2" type="checkbox" value="1" />
  <input name="checkbox_3" type="checkbox" value="1" />
  <input name="checkbox_4" type="checkbox" value="1" />
  <input name="checkbox_5" type="checkbox" value="1" />
  <input name="checkbox_6" type="checkbox" value="1" />
  <input name="checkbox_7" type="checkbox" value="1" />
  <input name="checkbox_8" type="checkbox" value="1" />
  <input name="checkbox_9" type="checkbox" value="1" />
  <input name="checkbox_10" type="checkbox" value="1" />[/code]

Now, for each checkbox the user checks, I want to update a MySQL query that will get values from each list corresponding to that number. For example, if they check boxes 1 and 2, I want the MySQL query to look like:

[code]"SELECT * FROM `table` WHERE (`list_number` = 1 OR `list_number` = 2)[/code]..etc

How would I generate this MySQL query most efficiently with ten or more checkboxes? I was thinking of using [code]foreach()[/code] but I'm not sure if that's going to work. If someone could point me in the right direction that would be great! Thanks!

Share this post

Link to post
Share on other sites
You'll wwant to give each checkbox the same name but prepend the name square brackets like so: checkbox[] that way any tickboxes that are checked get send as an array, which will help to produce your dynamic query. ALso you'll wan to give the checkbox a different value, say for checkbox1 use the value 1, for next checkbox give it a vlaue of 2 etc.

Heres a demo:

    $sql  =  'SELECT * FROM `table` WHERE (`list_number` = ';
    $sql .= implode(' OR `list_number` = ', $_POST['checkbox']) . ")";

    echo '<code>' . $sql . "</code><br /><br />\n";

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
for($i = 1; $i <= 10; $i++)
    echo "<input name=\"checkbox[]\" type=\"checkbox\" value=\"{$i}\" />&nbsp; &nbsp;Checkbox{$i}<br />\n  ";
  <input type="submit" name="submit" value="Generate Query" />

Share this post

Link to post
Share on other sites
Slightly easier is to put the checked values into a comma-delimited list

[code]$list = join (',', $_POST['checkbox']);    #--> 1,3,4,7,8 for example[/code]

Then the query becomes

[code]SELECT * FROM tablename WHERE list_number IN ($list)[/code]

Share this post

Link to post
Share on other sites


Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.