Php 在高级搜索中使用explode进行搜索时重复结果
我正在做基于标题的高级搜索,这是我的代码。首先,我搜索整个标题的基础上。如果找不到任何一本书,我会根据书名中的每个单词进行搜索 问题是,如果第二种情况下有两个或多个单词与标题匹配,那么它将打印重复的书籍Php 在高级搜索中使用explode进行搜索时重复结果,php,Php,我正在做基于标题的高级搜索,这是我的代码。首先,我搜索整个标题的基础上。如果找不到任何一本书,我会根据书名中的每个单词进行搜索 问题是,如果第二种情况下有两个或多个单词与标题匹配,那么它将打印重复的书籍 $qry="select * from books where quantity>0 "; if(isset($title)&&isset($submit1)) $qry.=" and title like '%".$title."%' "; $books=mysqli_q
$qry="select * from books where quantity>0 ";
if(isset($title)&&isset($submit1))
$qry.=" and title like '%".$title."%' ";
$books=mysqli_query($con,$qry);
$numrows=mysqli_num_rows($books);
if($numrows>0){
while($row=mysqli_fetch_assoc($books)){
//print books
}
}
else if(isset($submit1)&&isset($title)){
$words=explode(" ",$title);
$notfound=true;
foreach($words as $value){
$qry="select * from books where quantity>0 ";
$qry.=" and title like '%".$value."%' ";
$books=mysqli_query($con,$qry);
$numrows=mysqli_num_rows($books);
if($numrows>0){
while($row=mysqli_fetch_assoc($books)){
// print based on each word
}}
您应该更改SQL查询,使用
或
立即搜索任何单词,而不是对每个单词进行单独的查询并在查询后处理重复的单词。只是不要忘记括号,因为还有另一个条件
最终,你应该或多或少地得到这样的结果:
$words=explode(" ",$title);
$conditions = [];
foreach ($words as $word) {
$conditions[] = "title like '%" . $word ."%'";
}
$query = sprintf(
"select * from books where quantity > 0 and (%s)",
join(" or ", $conditions)
);
$books = mysqli_query($con, $query);
$numrows = $mysqli_num_rows($books);
...
您为什么不使用
或
,而是单独查询标题和每个单词?如果找到标题,则无需检查每个单词。所以我已经这样做了,但是为什么不在基于单词的查询中使用或?你不会得到任何复制品的。然后,它将给出quantity>0的所有结果。对您正在使用的代码范围使用全局数组。然后将来自所有不同查询的所有结果添加到该数组中,只要该项不在数组中。明白了。“或”on conditions“或”and“on conditions”的最佳方式是什么?$conditions
存储每个单词的like
条件。如果要搜索包含任何单词的标题,应使用或
将其加入,如果要查找包含所有单词的标题,应使用和
。