SELECT * FROM table其中列类似于'%variable%' - 任何顺序的多个单词

时间:2014-03-27 14:59:33

标签: php mysql

我为同事们编写了一个快速搜索页面,使用php查询数据库。他们的字符串被命名为$ wordvariable(他们也选择日期等,但这里并不重要),这是我到目前为止所做的事情:

$wordvariable = explode(" ", $wordvariable);
$wordvariable = implode("%", $wordvariable);
$Query = mysql_query(
    "SELECT * FROM table 
    WHERE (column1 like '%$wordvariable%' or column2 like '%$wordvariable%')
    AND logdatex between $TimeEarlier and $TimeNow"
) or die(mysql_error());
然而,

只搜索他们按照键入的顺序输入的单词,例如搜索"堆栈溢出"会发现"堆栈这是溢出"但是找不到"溢出堆栈"。我希望我已经正确地表达了这一点,任何帮助都将不胜感激

2 个答案:

答案 0 :(得分:0)

像这样的东西:

$where = "WHERE column1 LIKE '%" . implode("%' OR column1 LIKE '%", explode(" ", $wordvariable)) . "%'";

简而言之,只需explode $wordvariable空格,然后implode您想要的短语上的单词。

更详细,包括column2

$words  = explode(" ", $wordvariable);
$list1  = implode("%' OR column1 LIKE '%", $words);
$list2  = implode("%' OR column2 LIKE '%", $words);

echo $where = "WHERE (column1 LIKE '%$list1%') OR (column2 LIKE '%$list2%')";

答案 1 :(得分:0)

像这里更新您的代码:

$wordvariable = explode(" ", $wordvariable);

$Query = mysql_query(
  "SELECT * FROM  table
   WHERE (column1 like '%" . implode("%' OR column1 Like '%", $wordvariable) . "%'
   OR column2 like '%" . implode("%' OR column2 Like '%", $wordvariable) . "%')
   AND logdatex between $TimeEarlier and $TimeNow"
) or die(mysql_error());