【发布时间】:2015-10-20 10:10:05
【问题描述】:
我正在使用this script,我想修改/更新它以使其以这种方式工作:
在我的数据库中,例如:hello world, my name is John。当我搜索 Hello World 或 orld, m 或 name i 时,我想找到该项目,但如果我搜索 world hello 或 name John 它不起作用。所以,我正在寻找使它工作的方法。有人可以帮我吗?
非常感谢
index.php
<script type="text/javascript">
$(function(){
$(".search").keyup(function() {
var searchid = $(this).val();
var dataString = 'search=' + searchid;
if (searchid != '') {
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html) {
$("#result").html(html).show();
}
});
}
return false;
});
jQuery("#result").live("click", function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#searchid').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$('#searchid').click(function(){
jQuery("#result").fadeIn();
});
});
</script>
<style type="text/css">
body {
font-family: Tahoma, Geneva, sans-serif;
font-size: 15px;
}
.content {
width: 90%;
margin: 0 auto;
}
#searchid {
width: 90%;
border: solid 1px #000;
padding: 10px;
font-size: 14px;
}
#result {
position: absolute;
width: 70%;
padding: 15px;
display: none;
margin-top: -1px;
border-top: 0px;
overflow: hidden;
border: 1px #CCC solid;
color: white;
background-color: black;
}
.show {
padding: 4px;
border-bottom: 1px #999 dashed;
font-size: 12px;
height: 58px;
}
.show:hover {
background: #4c66a4;
color: #FFF;
cursor: pointer;
}
</style>
搜索.php
<?php
include('admin/db.php');
if($_POST)
{
$q = $_POST['search'];
$sql_res = mysql_query("select id, name, email, infos from autocomplete where name like '%$q%' or email like '%$q%' or infos like '%$q%' order by id LIMIT 100");
while ($row = mysql_fetch_array($sql_res))
{
$username = $row['name'];
$email = $row['email'];
$infos = $row['infos'];
$b_username = '<strong><font style="color: black; background-color: #ffff42">'.$q.'</strong></font>';
$b_email = '<strong><font style="color: black; background-color: #ffff42">'.$q.'</strong></font>';
$b_infos = '<strong><font style="color: black; background-color: #ffff42">'.$q.'</strong></font>';
$final_username = str_ireplace($q, $b_username, $username);
$final_email = str_ireplace($q, $b_email, $email);
$final_infos = str_ireplace($q, $b_infos, $infos);
?>
<div class="show" align="left">
<span class="name">
<?php echo $final_username; ?>
</span> <br/>
<?php echo $final_email; ?>
</span> <br/>
<?php echo $final_infos; ?><br/>
</div>
<?php }
} ?>
【问题讨论】:
-
MySQL
LIKE子句不够聪明,无法以不同的顺序查找单词的记录。最好的办法是将搜索查询拆分为单词,然后循环遍历每个单词,为出现的每个搜索结果添加一个点,然后按照它的点数对结果进行排序。 -
您还应该更新脚本以使用 MySQli 或 PDO。根据您使用的数据库,您可以尝试使用 MATCH() ... AGAINST。
标签: php jquery mysql autocomplete