我想使用jQuery Autocomplete插件创建用户搜索功能,并从我的MySQL数据库中获取信息。
我可以通过他的姓名,姓氏,电话号码或邮件地址搜索用户,然后显示所有匹配的用户
以下脚本有效,但有些东西搞乱了。 如果我正在搜索" BOUVIER Maxime"用户,它的工作原理。 但是,如果我写了#Max; BOUVIER",它就不再有用了。
这是我的剧本:
$("#user").autocomplete({
source: function (query, response) {
$.ajax({
url: "get_customer.php",
dataType: 'json',
data: query,
type: 'POST',
success: function (data) {
console.log(data);
response(data.map(function (value) {
return {
id: value.id,
value: value.nom,
email: value.email,
telephone: telephone
};
}));
}
});
},
minLength: 2,
delay: 200,
}});
这是我的php脚本:
$keyword = $_POST['term'];
$a_json = array();
$a_json_row = array();
$search_param= "%".$keyword."%";
$query = $db->prepare("SELECT id_client, nom, prenom, email,telephone FROM client WHERE nom LIKE :search OR prenom LIKE :search OR email LIKE :search OR telephone LIKE :search");
$query->bindParam(":search", $search_param);
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$a_json_row["id"] = $row["id_client"];
$a_json_row["nom"] = strtoupperFr($row["nom"]). " ".ucwords($row["prenom"]);
$a_json_row["email"] = $row["email"];
$a_json_row["telephone"] = $row["telephone"];
array_push($a_json, $a_json_row);
}
echo json_encode($a_json);
$db = NULL;
(我使用PDO模拟ON,对我的查询使用相同的var)
答案 0 :(得分:0)
如果您希望逐字搜索,则需要拆分字词。 替换这个:
$query = $db->prepare("SELECT id_client, nom, prenom, email,telephone FROM client WHERE nom LIKE :search OR prenom LIKE :search OR email LIKE :search OR telephone LIKE :search");
$query->bindParam(":search", $search_param);
$query->execute();
有了这个:
$where = "";
$arrKeyword = explode(" ", $_POST['term']);
if (!empty($arrKeyword)) {
foreach ($arrKeyword as $i => $word) {
$where .= " OR nom LIKE :search{$i} OR prenom LIKE :search{$i} OR email LIKE :search{$i} OR telephone LIKE :search{$i} ";
}
}
$sql = "SELECT id_client, nom, prenom, email,telephone
FROM client
WHERE FALSE
{$where} ";
$query = $db->prepare($sql);
if (!empty($arrKeyword)) {
foreach ($arrKeyword as $i => $word) {
$search = "%$word%";
$query->bindParam(":search{$i}", $search);
}
}
$query->execute();