Forum Moderators: coopster

Message Too Old, No Replies

Complex Query Options

         

webfoo

11:43 pm on Apr 6, 2010 (gmt 0)

10+ Year Member



I have a problem that is difficult to explain, please let me know if you need details:

I am making a PHP/MySQL system by which the user can filter the data in three simultaneous filters. The user's choice for each filter is stored in a cookie. One option for each filter is "All" which lets everything through the filter.

So I have cookies like so:
FilterA: All OR Choice 1 OR Choice 2
FilterB: All OR Choice 1 OR Choice 2
FilterC: All OR Choice 1 OR Choice 2

And Table Like this:
[pre]
| id | A | B | C | data |
| 1 | 1 | 2 | 1 | blah |
| 2 | 2 | 2 | 2 | blah |
| 3 | 1 | 1 | 2 | blah |
| 4 | 2 | 2 | 1 | blah |
.... and so on.
[/pre]


In the MySQL table, there are columns for each filter, with either Choice 1 or 2 in each record. "All" is never value in the table.
How can I create a SQL querey that will pull the right records out based on all three filters?

Thanks in advance.

astupidname

5:51 am on Apr 7, 2010 (gmt 0)

10+ Year Member



Should get you on track or close to it anyhow (note, the example assumes that the $Filter's can only be 'All' or 1 or 2, if there is any chance they could be messed with, should verify them prior to here):

$fa = ($FilterA != 'All') ? ' WHERE A = '.$FilterA : '';
$fb = ($FilterB != 'All') ? ((strlen($fa)) ? ' AND B = '.$FilterB : ' WHERE B = '.$FilterB) : '';
$fc = ($FilterC != 'All') ? ((strlen($fa) || strlen($fb)) ? ' AND C = '.$FilterC : ' WHERE C = '.$FilterC) : '';
$query = 'SELECT * FROM the_table'.$fa.$fb.$fc; //if all the $Filter's were 'All', $fa $fb & $fc will be blank strings, so should pull everything
$result = mysql_query($query);
//etc.. etc..

webfoo

12:46 pm on Apr 7, 2010 (gmt 0)

10+ Year Member



Thanks so much. Problem solved.