假如我在MySQL数据库中有一个书籍表,我想在'title'字段中搜索关键字(由用户在搜索字段中输入); 在PHP中执行此操作的最佳方法是什么?MySQL LIKE命令是最有效的搜索方式吗?
Vin*_*vic 21
是的,最有效的方法通常是在数据库中搜索.要做到这一点,你有三种选择:
所以这取决于你将实际寻找什么来决定什么是最好的.对于书籍标题,我提供了一个LIKE搜索精确的子串匹配,当人们知道他们正在寻找的书时很有用,还有一个FULLTEXT搜索来帮助找到类似于单词或短语的标题.我当然会在界面上给它们不同的名字,可能就像子串搜索一样精确,类似于全文搜索.
关于全文的一个例子:http://www.onlamp.com/pub/a/onlamp/2003/06/26/fulltext.html
Pau*_*xon 10
这里有一个简单的方法可以拆分一些关键字来构建一些子句,用于过滤这些关键字上的列,ANDed或ORed.
$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?
}
Run Code Online (Sandbox Code Playgroud)