使用mysql php搜索和匹配单词

时间:2015-02-04 06:23:02

标签: php mysql

我正在尝试将我的搜索查询的单词与sql数据库中的表格相匹配,但我没有这样做,请告诉我该怎么做。感谢

mysql table 'mytable'
ID | words
0  | cars 
1  | blue car
2  | red 
3  | green car
4  | tank
5  | car

Mysql查询

$query = "Select * from `mytable`";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
$w = $row['words'];
$i =  " ".$w." " ; 
}

搜索Word

$search = 'red car';

与数据库匹配

$mywords = split(" ",$i); 
$split_strings = preg_split('/[\ \n\,]+/', $search);
$result = array_intersect($split_strings, $mywords);
if(!empty($result))
{ 
echo 'Matched';
}
else {
echo 'Not Matched';
}

我想让它成为匹配的'但它回应了“不匹配”

1 个答案:

答案 0 :(得分:0)

我已运行此代码,我遇到的唯一问题是split函数,因为它已被弃用。所以我改变了

$mywords = split(" ",$i);

$mywords = preg_split('/[\ \n\,]+/',$i);

修复了你的阵列问题

  $data=array();
    while($row = mysqli_fetch_array($result, MYSQL_ASSOC))
    {
    $w = $row['words'];
    $i =  " ".$w." " ;
    $data[]=$i; 
    }
 for($i=0;$i<sizeof($data);$i++)
{   
$mywords=preg_split('/[\ \n\,]+/', $data[$i]);
$result = array_intersect($mywords,$search);
   if($result)
   {
      echo "Matched";
      break;
   }
}
if(!$result)
   {
     echo "No matched";
   }