简体   繁体   中英

Optional Variables in PHP/MySQL Drop down Search

I'm having a hard time finding a clear answer to this question on here... I'm trying to figure out how to filter a MySQL query with optional variables. For example, I want people to be able to select a month, or a year, or a state from drop downs... or they can select just two or all of these things.

Also, can this be done using $_GET so that the URL will be something like http://myurl.com/triathlon/?state=CA&month=January when the use submits the request?

You can see an example of where this would be use on the top of the following page: http://legfly.com/triathlon

Thanks a bunch and I hope this question was written in a way that makes sense. Thanks again.

Your php would be something like:

$query = "SELECT * FROM my_table";

$where_clause = array() ;
if($_GET['month'] != null){
    $where_clause[] = "`perma_month` = '$_GET[month]'";
}
if($_GET['year'] != null){
    $where_clause[] = "`perma_year` = '$_GET[year]'";
}
if($_GET['state'] != null){
    $where_clause[] = "`state` = '$_GET[state]'";
}
if(count($where_clause))
    $query .= " WHERE " . implode(' AND ' , $where_clause);

 $result = mysql_query($query) ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM