假设我有一张包含书籍信息的 MySQL 数据库表格,并且我想要在 'title' 字段中搜索用户在搜索框中输入的关键字,那么在 PHP 中如何最好地实现这个功能呢?使用 MySQL 的 LIKE
命令是最高效的搜索方式吗?
以下是一个简单的方法,您可以将一些关键字分解成一些子句,以便在这些关键字上过滤列,无论是AND还是OR。
$terms=explode(',', $_GET['keywords']);
$clauses=array();
foreach($terms as $term)
{
//remove any chars you don't want to be searching - adjust to suit
//your requirements
$clean=trim(preg_replace('/[^a-z0-9]/i', '', $term));
if (!empty($clean))
{
//note use of mysql_escape_string - while not strictly required
//in this example due to the preg_replace earlier, it's good
//practice to sanitize your DB inputs in case you modify that
//filter...
$clauses[]="title like '%".mysql_escape_string($clean)."%'";
}
}
if (!empty($clauses))
{
//concatenate the clauses together with AND or OR, depending on
//your requirements
$filter='('.implode(' AND ', $clauses).')';
//build and execute the required SQL
$sql="select * from foo where $filter";
}
else
{
//no search term, do something else, find everything?
}
你还可以在MySQL手册中查看soundex函数(soundex,类似声音),http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_soundex。如果例如通过LIKE或=进行严格检查没有返回任何结果,这个函数可以返回这些匹配项。
Paul Dixon的代码示例很好地传达了基于LIKE的方法的主要思想。
我只想添加这个可用性想法:在界面中提供一个(AND | OR)单选按钮集,将默认设置为AND,然后如果用户的查询结果为零(0)匹配并且包含至少两个单词,则响应一个选项,例如:
"抱歉,未找到与您的搜索短语匹配的任何结果。扩展搜索以匹配短语中的任何单词?
也许有更好的表述方式,但基本思想是引导人们进行另一个查询(可能会成功),而不需要用户考虑AND和OR的布尔逻辑。
我认为如果是一个单词,Like 是最有效的方式。多个单词可能会使用 explode 函数进行拆分,如前所述。然后可以循环并单独用于通过数据库搜索。如果返回相同的结果两次,则可以通过将值读入数组来进行检查。如果它已经存在于数组中,请忽略它。然后使用 count 函数,您将知道在循环打印时何时停止。可以使用 similar_text 函数进行排序。百分比用于对数组进行排序。这是最好的。