无法过滤空格,Query会返回所有用户

时间:2011-09-16 06:55:06

标签: php html sql filter

我有一个用户界面,用户可以在其中键入一个人的名字和姓氏。 只要我在搜索框中没有输入任何内容,就不会找到任何用户。但是只要我输入空格,就会返回数据库中的每个用户。我修剪输入字符串并检查空格:

if (isset($_GET['lastname'])) {
    $lastname_value = trim($_GET['lastname']);
    //This Line is only used for setting the Text again in the Search Box       
    $tpl->setVariable('ss-search-lastname-value', $lastname_value);
}
if(isset($_GET['firstname'])) {
    $firstname_value = trim($_GET['firstname']);
    $tpl->setVariable('ss-search-firstname-value',$firstname_value);
}

之后我编写了搜索查询:

$sql = "SELECT e.`user_id`, e.`firstname`, e.`lastname`, e.`email`
            FROM `employees` as e
            WHERE 1";
if($lastname_value!="") {
    $sql .=" AND e.`lastname` ='$lastname_value'";
}
if($firstname_value!="") {
    $sql .=" AND e.`firstname` ='$firstname_value'";
}

正常搜索返回具有正确名字和姓氏的预期用户,如果我什么也没输入并开始搜索,则不会返回任何结果。但是,搜索框中的单个空格和我获得所有用户。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您需要先决定是否要搜索:

$doSearch = false;
$hasLastname = $lastname_value != "";
$hasFirstname = $firstname_value != "";
$doSearch = $hasLastname || $hasFirstname;

if ($doSearch)
{
    $sql = "SELECT e.`user_id`, e.`firstname`, e.`lastname`, e.`email`
            FROM `employees` as e
            WHERE 1";
    if($lastname_value!="") {
        $sql .=" AND e.`lastname` ='$lastname_value'";
    }
    if($firstname_value!="") {
        $sql .=" AND e.`lastname` ='$firstname_value'";
    }
    ...
}