0

我使用 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 ";

    }
  }
?>
4

3 回答 3

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 ";

    }
  }
于 2013-06-28T13:02:32.107 回答
0

如果你只是想修改 SQL 查询,你应该能够做这样的事情。

select name, surname from users where CONCAT(name, ' ', surname) like '%value%'

这将采用名字和姓氏,并在它们之间放置一个空格,然后进行搜索。

这意味着当您的用户点击空格键时,它仍然会找到您正在寻找的用户。

于 2013-06-28T13:14:37.390 回答
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%')";
}
于 2013-06-28T13:35:46.227 回答