Jump to content

PHP Checkboxes, dynamically change MySQL query


DillyDong

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!
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:
[code=php:0]<?php

if(isset($_POST['submit']))
{
    $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">
  <?php
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" />
</form>[/code]
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]

Archived

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

×
×
  • Create New...

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.