Forum Moderators: coopster
Working on a personal site where I need to perform a query based on checkboxes. Have read most of the topics for this, but still haven't quite found a solution.
What I have is a form that has various checkboxes (we can call them $field1 through $field20). Each field corresponds to a row in the database that is 'enum' with 'Yes' or 'No' values. I realize that if the boxes aren't checked, nothing is sent via post headers, so I have allowed for this by checking each field to see if it's empty, if so, set the variable $fieldx = 'No'.
So far, so good...but here's where I need a little help. The query (for ease of use at this time) selects everything from the database, but I need the query to do a "where $field1 = 'Yes', $ field2 = 'Yes', and so forth.
The query can use 'or' comparisons as I only need to return the row ID which matches the various checkbox input.
Ideas, suggestions are most certainly welcome....
I have a site with a membership profile that is accessible by all viewers (of course not all data!)
what I have done is first using a form where a member has the choice to enter yes or no for
profile (yes for all viewers, no for restricted to members access)
then I createda field that I named yes_no
that field indeed gets only yes or no
then:
<?
//Go back into PHP mode.
$results = mysql_query("SELECT * FROM profile where yes_no like 'yes". $query ."%' ORDER BY last_name ASC LIMIT $page, $limit");
while ($data = mysql_fetch_array($results))
{
?>
// and to check on your data
<td width="33%" align="left" valign="top"><font color="#990000" size="2">First Name: </font> <font size="3"><?=$data["first_name"]?></font></td>
so you can modif the above and fit it to your need
One thats done, if you only want to return the records that match the ticked boxes (i.e. dont care about the other boxes) use an array loop to build your SQL statement... e.g.
$SQL="SELECT * FROM table WHERE ";
//$_GET['item'] is an *array* because of the naming
//Run through each and build the sql statements into a list
foreach($_GET['item'] as $key => $value)
{$item_set[]="item$key='$value'";}
//join up the statements with ANDs between
$SQL.=implode($item_set," AND ");
$result=mysql_query($SQL);
NB: This is horrendously unsecure (do some checks on the incoming data, to make sure its just "yes/no" and the field names are real)
In something I'm working on, I've used array names in the database fields also (surround with `backticks`) to make things easier on merging stored data with incoming.
Im not in a position to check the code at the moment, but if you need any more help, or I've missed the point entirely let me know :)