2012-09-19 66 views
1

我試圖想出一個搜索功能MySQL邏輯我在我的頁面上。它是一個簡單的表單,用戶可以選擇填寫搜索條件。條件(s)作爲參數發送到生成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()條件,但我仍然無法拿出正確的代碼,做我所需要的。如果有人能指引我正確的方向,我自己就可以完成其餘的工作。解決這類問題的任何其他方法也是受歡迎的。

+0

是你所檢查的條件? –

+0

檢查PHP變量是否有用戶輸入值或設置爲null(在控制器的php文件中完成)。我認爲DTukans給出的解決方案很好。連接sql邏輯取決於它的PHP變量是否爲null。我會嘗試並返回結果。 – user1683645

回答

0

如果我理解你的問題,然後簡單的方法是使用的if else來構建SQL查詢,例如

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

這應該工作,但我有一個小問題。如果用戶沒有在表單中輸入任何內容,則分配給變量的空值在var_dump和條件!is_null($ var)變爲true時爲空字符串「」。我的var_dump()的形式如下:string(7)「subzero」 string(0)「」 string(0)「」 string(0)「」這個結果是在用戶只選擇輸入其中一個形式。其他變量設置爲空;由於沒有輸入。我得到的問題是!is_null($ var)返回true,錯誤的字符串連接到SQL邏輯。 – user1683645

+0

好吧,我想出了一個解決方案。我用空來代替,但仍然想知道如何給變量賦值null,以便將來可以使用is_null。 $ var = null;產生了一個像這樣的空字符串「」。謝謝您的幫助。不能upvote,因爲我沒有15聲望:/ – user1683645