我有一个搜索表单,用户应该输入一个单词。到目前为止,它工作得很好,但是当我输入带有 2 个或更多空格的单词时,查询不会返回任何内容(空)。
$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
它不会返回任何内容,甚至不会返回“未找到错误”。
我该如何解决这个问题?
我通过替换 $search
尝试了 PHPMyAdmin
查询返回匹配,甚至与core 2 dou
匹配,甚至添加像
核心2斗计算机
我确信问题出在发送查询或处理它的 php 方式上,我只是无法弄清楚
最佳答案
您需要将模式用引号引起来。而你有
"... REGEXP ^$search|$search\$ ..."
你需要有
"... REGEXP \"^$search|$search\$\" ..."
此外,您应该至少使用 mysql_real_escape_string
转义 $search
,除非您希望网站访问者能够run random SQL against your database .
关于php - 查询具有多个空格的短语不会返回任何结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7055138/