会员搜索功能

时间:2012-09-19 16:38:55

标签: php mysql search

我试图为我的页面上的搜索功能提出MySQL逻辑。它是一个简单的表单,用户可以选择填写搜索条件。标准作为参数发送到生成mysql逻辑的函数。这是PHP控制器文件中的内容:

   case 'search':
         if((empty($_POST['username'])) && (empty($_POST['firstname'])) && (empty($_POST['lastname']))
                && (empty($_POSt['agemin'])) && (empty($_POST['agemax'])) && (empty($_POST['country']))){
                $members = get_all_username();
         } else {
            if(isset($_POST['username'])){
                $otheruser = $_POST['username'];
            } else { $otheruser = null; }
            if(isset($_POST['agemin'])){
                $ageMin = $_POST['agemin'];
            } else { $ageMin = null; }
            if(isset($_POST['agemax'])){
                $ageMax = $_POST['agemax'];
            } else { $ageMax = null; }
            if(isset($_POST['country'])){
                $country = $_POST['country'];
            } else { $country = null; }
            //if(isset($_POST['isonline']))

        $members = search_members($otheruser, $ageMin, $ageMax, $country);
        }
        include('displaySearch.php');
        break;

因此,如果未设置任何内容,则会生成并显示所有成员的完整列表。如果设置了任何输入,则调用此函数:

function search_members($username, $ageMin, $ageMax, $country){
    global $db;
    $query = "SELECT username FROM profiles WHERE username = :username 
        AND age > :ageMin AND age < :ageMax AND country = :country";
    $statement = $db->prepare($query);
    $statement->bindValue(':username', $username); $statement->bindValue(':ageMin', $ageMin);
    $statement->bindValue(':ageMax', $ageMax); $statement->bindValue(':country', $country);
    $statement->execute();
    if($statement->rowCount() >= 1){
        return $statement->fetchAll();
    } else {
        return false;
    }
}

mysql逻辑显然是错误的。 我需要一组条件(如果可能的话,在MySQL逻辑中)检查PHP变量的值,如果没有则在查询数据库时不应该考虑它。所以如果只是用户名是在表单中设置其他变量不应包含在SQL逻辑中。

我已经查找了MySQL IF()条件,但我仍然无法提供能够满足我需要的正确代码。如果有人可以指出我正确的方向,我将能够自己做其余的事情。任何其他解决此类问题的方法也是受欢迎的。

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题,那么简单的方法是使用if else来构建sql查询,例如

$sql = "SELECT username FROM profiles WHERE 1 "
if (!is_null($username)) {
    $sql .= " AND username = :username ";
}
// All other checks