我使用php和jquery创建了一个自动建议搜索框。用户提示在名为user的表中插入名称和姓氏以查找我的数据库中存在的某个人。表用户拥有2列,名称和姓氏。当你输入名字时我的搜索工作正常,但按空格移动后输入姓氏并没有给出任何结果。按空格键时似乎出现了整个问题。知道怎么解决吗?
这是我的jquery代码:
$(document).ready(function(){
$('#search_form_1').keyup(function(){
var value = $(this).val();
if(value != ''){
$('#search_result').show();
$.post('search_form.php', {value: value}, function(data){
$('#search_result').html(data);
});
}else{
$('#search_result').hide();
}
});
});
这是我的PHP代码:
<?php
if(isset($_POST['value'])== true && empty($_POST['value']) == false){
$value = mysql_real_escape_string($_POST['value']);
$query = mysql_query(" SELECT `surname`, `name` FROM `users` WHERE (`surname` LIKE '$value%' OR `name` LIKE '$value%') OR (`name` LIKE '$value%' OR `surname` LIKE '$value%') ");
while($run = mysql_fetch_array($query)){
$surname = $run['surname'];
$name = $run['name'];
echo " $surname $name ";
}
}
?>
答案 0 :(得分:2)
您必须拆分搜索:
<?php
if(isset($_POST['value'])== true && empty($_POST['value']) == false){
$value = mysql_real_escape_string($_POST['value']);
$name_and_surname = explode(" ", $value);
$name = $name_and_surname[0];
$surname = $name_and_surname[1];
$q = " SELECT `surname`, `name` FROM `users` WHERE (`surname` LIKE '$name%' OR `name` LIKE '$name%') OR (`name` LIKE '$surname%' OR `surname` LIKE '$surname%') ";
// check your query one more time
echo $q;
$query = mysql_query($q);
while($run = mysql_fetch_array($query)){
$surname = $run['surname'];
$name = $run['name'];
echo " $surname $name ";
}
}
答案 1 :(得分:0)
如果你只想修改SQL查询,你应该能够做这样的事情。
select name, surname from users where CONCAT(name, ' ', surname) like '%value%'
这将采用名字和姓氏,并在它们之间放置一个空格,然后搜索它。
这意味着当您的用户点击空格键时,它仍会找到您正在寻找的用户。
答案 2 :(得分:0)
未授予编辑,因此以下是代码:
$value = mysql_real_escape_string($_POST['value']);
$names = explode(" ", $value);
if(count($names)>1){
$name = $names[0];
$surname = $names[1];
$q = "SELECT surname, name FROM users WHERE (name LIKE '$name%' AND surname LIKE '$surname%') OR (name LIKE '$surname%' AND surname LIKE '$name%')";
}else{
$q = "SELECT surname, name FROM users WHERE (name LIKE '$value%' OR surname LIKE '$value%')";
}