我想用这部分代码创建一个高级搜索功能
//search.php?name= &country= &city= &age= &gender=
$search_name = 0;
$search_country = 0;
$search_city = 0;
$search_age = 0;
$search_gender = 0;
$allow_querry = false;
if((isset($_GET["name"])) AND ($_GET["name"] != "")) {
$name = $_GET["name"];
$search_name = 1;
}
if((isset($_GET["country"])) AND ($_GET["country"] != "")) {
$country = $_GET["country"];
$search_country = 1;
}
if((isset($_GET["city"])) AND ($_GET["city"] != "")) {
$city = $_GET["city"];
$search_city = 1;
}
if((isset($_GET["age"])) AND ($_GET["age"] != "")) {
$age = $_GET["age"];
$search_age = 1;
$age = date('Y', strtotime('-'.$age.' years'));
}
if((isset($_GET["gender"])) AND ($_GET["gender"] != "")) {
$gender = $_GET["gender"];
$search_gender = 1;
}
但是,要摆脱所有这些ifs ....
if (($search_name==1) AND ($search_country==1) AND ($search_city==1) AND ($search_age==1) AND ($search_gender==1) ){
}else if(($search_name==1) AND ($search_country==0) AND ($search_city==0) AND ($search_age==0) AND ($search_gender==0) ){
}
.....等等...... = 32如果陈述
我使用了这种格式的开关案例功能:
switch($search_name . $search_country . $search_city . $search_age . $search_gender) {
case 11111 :
$query=mysql_query("SELECT * FROM users WHERE `username` LIKE '%" . $name . "%' OR `country` LIKE '%" . $country . "%' OR `city` LIKE '%" . $city . "%' OR `birth_month` LIKE '%" . $age . "%' OR `sex` LIKE '%" . $gender . "%' ");
$allow_querry = true;
break;
case 11110 :
$query=mysql_query("SELECT * FROM users WHERE `username` LIKE '%" . $name . "%' OR `country` LIKE '%" . $country . "%' OR `city` LIKE '%" . $city . "%' OR `birth_month` LIKE '%" . $age . "%' ");
$allow_querry = true;
break;
等32例
您是否知道其他方法可以让它看起来更漂亮或者更容易编写,假设我有数百种组合?
答案 0 :(得分:1)
假设您不需要允许and
/ or
变体,只需构建一个选项数组,最终sql崩溃:
$options = array();
if( ... do city search) {
$options[] = '`city` LIKE "$name"';
}
if( ... do country search ) {
$options[] = '`country` LIKE "$name"';
}
etc...
$where_clause = implode(' OR ', $options);
$sql = "SELECT ... WHERE $where_clause";
请注意,您很容易受到sql injection attacks的攻击。</ p>
或者,您也可以使用fulltext
搜索,只搜索您需要的特定字段:
if (...city search) {
$fields[] = 'city';
}
etc...
$field_list = implode(', ', $fields);
$sql = "SELECT ... WHERE MATCH($fields) AGAINST '$name'"