我试图通过在多个字段中搜索多个术语来从MySQL数据库中获取结果。下面的脚本工作正常,但不是我需要它的方式,我很难找到一种doint方式。
目前,如果我搜索" apple peaches" ,它将返回每个包含" apples" 或的结果" peaches" 在任何领域。即如果一条记录有" apples" 但不是" peaches" 它会产生一个结果。
对于预期的行为,我应该只在给定记录中找到任何字段上的所有搜索词时得到结果。即可以在字段f1上找到" apples" ,在字段f2上找到" peaches" 。如果只找到" apples" ,则不是结果。
<?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();
?>
感谢您的输入
答案 0 :(得分:1)
查看全文索引和查询:
http://www.devarticles.com/c/a/MySQL/Getting-Started-With-MySQLs-Full-Text-Search-Capabilities/
比使用类似语句更好的方法。
答案 1 :(得分:0)
请考虑以下事项:
$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%"
然后可以将<条> $条件作为WHERE条件插入到查询中。