查询 PHP/MySql AND/OR 以进行高级搜索
问题描述:
我是 php 和 mysql 的新手,所以我的查询需要一些帮助.这是我的 sql 查询
I'm new to php and mysql so I need some help with my query. This is my sql query
SELECT * FROM table1 WHERE (Name LIKE '%$keyword%' OR ZipCode LIKE '%$keyword%') AND Category LIKE '$category' AND Country LIKE '$country' LIMIT $start, $limit
现在我想做的是
- 此查询应使用带有 name 关键字的文本字段搜索带有 Name 或 ZipCode 的列名称.即关键字与 Name 列或 ZipCode 匹配.
- 如果未输入关键字并且仅从下拉列表中选择了一个国家/地区,该查询也应该有效.
- 如果未输入关键字或国家/地区,并且仅从下拉列表中选择了一个类别,则查询也应该有效.
更简单地说,如果选择了事物关键字、国家或类别中的任何一个,则搜索应相应地显示结果.此外,如果输入所有字段,它也应该有效.我设法做到了一半,但有时它会给我错误的结果.请帮忙.
In more simple words if either of the things keyword, country or category is selected the search should display results accordingly. Moreover it should also work if all the fields are input. I managed to do half of it but sometimes it gives me wrong results. Please help.
答
您可以在运行时检查设置了哪些字段并进行相应查询.你可以这样做:
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'"
}