我试图通过在多个字段中搜索多个术语从MySQL数据库中获得结果。下面的脚本正在工作,但并不完全是我需要它的方式,而且我很难找到一种方法来执行它。
目前,如果我搜索“苹果桃子”,它将返回任何字段中有“苹果”或“桃子”的所有结果。也就是说,如果一个记录有“苹果”而没有“桃子”,它就会产生一个结果。
对于预期的行为,只有在给定的记录中找到任何字段上的所有搜索条件时,我才会得到结果。例如,“苹果”可以在田间f1和“桃子”在田间f2。如果只找到“苹果”,那就不是结果了。
<?php
if (!isset($_REQUEST['term'])) exit;
$dblink = mysql_connect('localhost', 'root', 'pass') or die(mysql_error());
mysql_select_db('mytable');
mysql_set_charset('utf8', $dblink);
// query the database table for strings that match 'term'
$lcSearchVal = mysql_real_escape_string($_REQUEST['term']);
$lcSearchVal = explode(' ', $lcSearchVal);
$sql = 'SELECT id, f1, f2, f3, f4 FROM mytable
WHERE (';
$parts = array();
foreach($lcSearchVal as $lcSearchWord) {
if ($lcSearchWord <> "") {
$parts[] = '`id` LIKE "%' . $lcSearchWord . '%"';
}
if ($lcSearchWord <> "") {
$parts[] = '`f1` LIKE "%' . $lcSearchWord . '%"';
}
if ($lcSearchWord <> "") {
$parts[] = '`f2` LIKE "%' . $lcSearchWord . '%"';
}
if ($lcSearchWord <> "") {
$parts[] = '`f3` LIKE "%' . $lcSearchWord . '%"';
}
if ($lcSearchWord <> "") {
$parts[] = '`f4` LIKE "%' . $lcSearchWord . '%"';
}
}
$sql.= implode(' OR ', $parts) . ') order BY id desc limit 0,10';
$rs = mysql_query($sql, $dblink);
// loop through each string returned and format the response for jQuery
$data = array();
$data[] = array('value' => "", 'label' => " >> Last 10 results:", 'desc' => "");
if ($rs && mysql_num_rows($rs)) {
while ($row = mysql_fetch_array($rs, MYSQL_ASSOC)) {
if (strlen($row['f3']) > 250) {
$row['f3'] = substr($row['f3'], 0, 250) . " [...]";
}
$data[] = array('value' => $row['id'], 'label' => $row['id'] . '/' . $row['f1'] . ' (' . $row['f2'] . ') ' . $row['f4'], 'desc' => $row['f3']);
}
}
// jQuery wants JSON data
echo json_encode($data);
flush();
?>谢谢你的意见
发布于 2012-08-30 22:45:54
请考虑以下几点:
$lcSearchVal = 'one two three';
$lcSearchVal = explode(' ', $str);
foreach ($lcSearchVal as &$lcSearchWord) {
$lcSearchWord = '`id` LIKE "%' . $lcSearchWord . '%" AND ';
}
$conditions = rtrim(implode('', $val), ' AND ');
echo $conditions; //returns `id` LIKE "%one%" AND `id` LIKE "%two%" AND `id` LIKE "%three%"然后可以将$conditions作为WHERE条件插入到查询中。
发布于 2012-08-30 22:40:05
查看全文索引和查询:
http://www.devarticles.com/c/a/MySQL/Getting-Started-With-MySQLs-Full-Text-Search-Capabilities/
比用like语句来做这类事情要好得多。
https://stackoverflow.com/questions/12206421
复制相似问题