[英]Query for PHP/MySql AND/OR for an advanced search
I'm new to php and mysql so I need some help with my query. 我是php和mysql的新手,因此我的查询需要一些帮助。 This is my sql query 这是我的SQL查询
SELECT * FROM table1 WHERE (Name LIKE '%$keyword%' OR ZipCode LIKE '%$keyword%') AND Category LIKE '$category' AND Country LIKE '$country' LIMIT $start, $limit
Now what I want to do exaclty is 现在我想做的是
In more simple words if either of the things keyword, country or category is selected the search should display results accordingly. 用更简单的话说,如果选择了things关键字,country或category之一,则搜索将相应地显示结果。 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'"
}
I would suggest using several different queries (one for each combination of search parameters), using php to either decide which to use or dynamically build one with php. 我建议使用几个不同的查询(每个搜索参数组合一个),使用php决定使用哪个查询或使用php动态构建一个查询。
Note that using a like starting with a % is likely to be quite slow. 请注意,使用以%开头的like可能会非常慢。
If you really wanted to do it as one statement (and I don't recommend it) then:- 如果您真的想做一个声明(我不建议这样做),那么:-
SELECT *
FROM table1
WHERE (Name LIKE '%$keyword%' OR ZipCode LIKE '%$keyword%' OR '$keyword' = '')
AND (Category = '$category' OR '$category' = '' )
AND (Country = '$country' OR '$country' = '' )
LIMIT $start, $limit
Or to dynamically build it up 或动态构建
$ConditionArray = array();
if ($keyword != '') $ConditionArray[] = "(Name LIKE '%$keyword%' OR ZipCode LIKE '%$keyword%' OR '$keyword' = '')";
if ($category != '') $ConditionArray[] = "Category = '$category'";
if ($country != '') $ConditionArray[] = "Country = '$country'";
if (count($ConditionArray) > 0)
{
$query = "
SELECT *
FROM table 1
WHERE ".implode(' AND ', $ConditionArray);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.