PHP的if语句条件置换

rdlzhqv9  于 2023-04-19  发布在  PHP
关注(0)|答案(1)|浏览(111)

我试图创建一个先进的搜索功能与这部分代码

// search.php?name= &country= &city= &age= &gender=
$search_name = 0;
$search_country = 0;
$search_city = 0;
$search_age = 0;
$search_gender = 0;
$allow_query = 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;
  }

但是,为了摆脱所有这些如果……

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个if语句
我使用了如下格式的switch case函数:

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_query = 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_query = true;
   break;

32个病例
假设我有几百种组合,你知道有什么其他的方法可以让它看起来更好或者写起来更容易吗?

eyh26e7m

eyh26e7m1#

假设你不需要考虑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的攻击。
或者,您也可以使用fulltext搜索,只搜索您需要的特定字段:

if (...city search) {
   $fields[] = 'city';
}
etc...
$field_list = implode(', ', $fields);

$sql = "SELECT ... WHERE MATCH($fields) AGAINST '$name'"

相关问题