I have a web application that shows a list of events taken from a mysql db and presented to a user.
The user can then filter the results according to several (8-10) 'types'
My question is, how should I approach this? Basically what I need to do is take the user input for the filter (in $_GET
) and then find out which types he is looking to filter and according to that, change my sql query.
How do I do it in a way that is not very com开发者_高级运维plex? I thought of using many 'if' or 'case' statements, but i'm not sure if that's the best solution as its a lot of coding for a very simple thing..
Can anyone give me some advice? Thanks,
Example DB:
EVENT_ID EVENT_NAME EVENT_TYPE
1 test regular
2 test2 vip
3 test4 testtype
...
Example $_GET:
$_GET['regular'] = 'on'
...
you should probably create an array of types using checkboxes
<input type="checkbox" name="types[]" value="regular" /> Regular
<input type="checkbox" name="types[]" value="vip" /> VIP
then you would have an array of types with $_REQUEST['types']...
echo implode(",",$_REQUEST['types]); // for example
Well it depends if you actually store event_types as string (you shouldnt).
If you change them to int you could simply do
$query = "select * from events";
if(isset($_REQUEST['types'])){
$query .= "and event_types in (".implode(",",$_REQUEST['types']).")";
}
If you keep them as string in you db you could do the same thing but you'll have to had '' around the values...
of course you'll have to secure this
Is it supposed to allow multiply selections or only 1 filter selection. If 1 you could use the case function easy or you could use the onchange function of javascript.
Takes GET from a number of checkboxes and creates SQL query. You need to change column names and the $getOptions array. The key of a $getOptions element is the name of the type.
$getOptions = array(
'regular' => $_GET['regular'],
'vip' => $_GET['vip'],
'testtype' => $_GET['testtype']
);
$sql = "SELECT * FROM events";
$sqlOptions = array();
foreach($getOptions as $key => $value)
{
if($value == 'on')
{
$sqlOptions[] = $key;
}
}
if(!empty($sqlOptions))
{
$sql .= " WHERE EVENT_TYPE IN ('" . implode("','", $sqlOptions) . "')";
}
// Execute $sql
精彩评论