如果搜索的关键字超过2个,则PHP搜索无效

时间:2017-02-16 06:47:29

标签: php mysql search

我正在尝试构建一个搜索框,它将搜索2列。

html

<div class="autocomplete-list1">
    <input type="text" class="searchpropertyinputs areaname-list-completed" name="buildingorlocation" id="buildingorlocation" placeholder="Building or Location" onkeyup="autofillbuildingorlocation()" maxlength="50" />
    <ul class="areaname-list searchpropertyinputs" id="property_buildingorlocation_list"></ul>
</div>

PHP

$property_buildingorlocation = ($_GET['buildingorlocation']);
$property_buildingorlocation = str_replace(',', ' ', $property_buildingorlocation);


$select = $con->prepare(

"SELECT 
    * 
from 
    tbl_property 
WHERE 
    property_buildingname LIKE '%$property_buildingorlocation%' 
    OR property_areaname LIKE '%$property_buildingorlocation%'");

$select->setFetchMode(PDO::FETCH_ASSOC);
$select->execute();

如果我输入最多两个关键词,如麦迪逊花园,那么结果会来,但如果我把三个像麦迪逊花园之路那么没有结果......任何人都可以启发我...

1 个答案:

答案 0 :(得分:0)

请尝试以下代码:

<?php
$property_buildingorlocations = array_filter(explode(',', $_GET['buildingorlocation']));
$query = "SELECT * from tbl_property ";
$count = count($property_buildingorlocations);
if($count){
   $query .=" WHERE ";
}
$i = 0;
foreach ($property_buildingorlocations as $property_buildingorlocation){
   $query .= "property_buildingname LIKE '%".trim($property_buildingorlocation)."%'";
   if(++$i !== $count) {
      $query .=" OR ";
   }

}



$select = $con->prepare($query);

$select->setFetchMode(PDO::FETCH_ASSOC);
$select->execute();