查询包含多个空格的短语将不返回任何结果


Querying for phrase with more than one space returns nothing

我有一个搜索表单,用户应该输入一个单词。到目前为止,它工作得很好,但当我输入一个有2个或更多空格的单词时,查询返回none(空)。

    $search = $_POST['srch'];
    if (!$search == "")
    {
    $con = mysql_connect('nnnnn', 'nnnnn', 'nnnn');
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
    mysql_select_db("nnnnnnn", $con);
    $search = mysql_real_escape_string($search);
    $sql = "SELECT * FROM `computers` WHERE `MODEL` REGEXP '$search|$search'$' OR
    `DESCR`'n"
        . "REGEXP '^$search|$search'$' LIMIT 0, 30 ";
    // here check if there is any content
if (mysql_fetch_array($result))
{
while($row = mysql_fetch_array($result))
{// here just echoing the returned content 
}
}else echo "not found";
    }echo "enter a word"! ;

例如,如果我输入core 2,它会返回所有匹配的结果。

但是如果我写core 2 dou,它不会返回任何东西,甚至不是"not found error"。

我该如何解决这个问题?

我尝试了PHPMyAdmin通过替换$search

和查询返回结果甚至匹配core 2 dou,甚至添加像

这样杂乱的单词

core 2 dou computers

我确信问题是在PHP发送查询或处理它的方式,我只是不能弄清楚

你需要用引号把模式括起来。而你有

"... REGEXP ^$search|$search'$ ..."

你需要有

"... REGEXP '"^$search|$search'$'" ..."

此外,您应该至少使用mysql_real_escape_string来转义$search,除非您希望站点访问者能够对您的数据库运行随机SQL。

既然你说任何帮助将是感激的,如果你只是想搜索一个字符串,一个更简单的方法是使用LIKE代替REGEXP,例如,

MODEL LIKE '%$search%'

还有,我不知道你为什么要重复用'|'分隔的$search

顺便说一下,如果有多个空格的问题,很容易用单个空格替换,像这样:
$search = implode(' ', preg_split("/'s+/", $search));