自从提出这个问题以来已经有一段时间了,自从提出这个问题以来我已经打开了它,但直到现在才有时间尝试并回答,希望答案仍然有帮助:)
为了清楚起见,我将解释我的假设
我的解决方案以空格分隔单词的形式输入,输入的任何单词都必须存在于结果中,但可以来自任一字段“business_name 或 business_description”,如果没有给出输入,则执行通用查询。
我为输入数据添加了一些基本的清理并简化了代码
<?php
$keywords = trim(filter_var($_REQUEST["keywords"], FILTER_SANITIZE_STRING, FILTER_SANITIZE_MAGIC_QUOTES));
$query = "SELECT * FROM business_listing";
if(strlen($keywords) > 0)
{
$words = explode(" ",$keywords);
$query .= " WHERE ";
foreach ($words as $word)
{
$safeWord = mysql_real_escape_string($word);
$query .= "(business_name LIKE '%" . $safeWord . "%' OR business_description LIKE '%" . $safeWord . "%') AND ";
}
$query = rtrim($query, " AND");
}
echo $query;
?>
如果将 php 保存到文件 search.php 中,则可以通过 url 中的以下参数运行它
search.php?keywords=gopher test fish
这将产生以下 SQL 语句
SELECT * FROM business_listing WHERE (business_name LIKE '%gopher%' OR business_description LIKE '%gopher%') AND (business_name LIKE '%test%' OR business_description LIKE '%test%') AND (business_name LIKE '%fish%' OR business_description LIKE '%fish%')
对于 Sanoj Sharma 的 santa napa 请求,它将产生
SELECT * FROM business_listing WHERE (business_name LIKE '%santa%' OR business_description LIKE '%santa%') AND (business_name LIKE '%napa%' OR business_description LIKE '%napa%')