且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

查询 PHP/MySql AND/OR 以进行高级搜索

更新时间:2023-01-31 08:56:55

您可以在运行时检查设置了哪些字段并进行相应查询.你可以这样做:

You can check which of the fields are set and make query accordingly at runtime. something like this you can do:

$query = "";
$keyword = $_REQUEST['keyword'];
$country = $_REQUEST['country'];
$category = $_REQUEST['category'];
if(isset($keyword)){//if keyword set goes here
   $query = "SELECT * FROM table1 WHERE Name LIKE '%$keyword%' OR ZipCode LIKE '%$keyword%' OR country LIKE '%$keyword%'";
   if(isset($category)){
     $query .= "AND category LIKE '$category'";
   }
   if(isset($country)){
     $query . = "AND country LIKE '$country'"
   }
}else if (isset($category)){ //if keyword not set but category set then goes here
  $query = "SELECT * FROM table1 WHERE category LIKE '$category'";
  if(isset($country)){
    $query . = "AND country LIKE '$country'";
  }
}else if(isset($country)){//if only country set goes here
  $query = "SELECT * FROM table1 WHERE country LIKE '$country'"
}