我試圖想出一個搜索功能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()條件,但我仍然無法拿出正確的代碼,做我所需要的。如果有人能指引我正確的方向,我自己就可以完成其餘的工作。解決這類問題的任何其他方法也是受歡迎的。
是你所檢查的條件? –
檢查PHP變量是否有用戶輸入值或設置爲null(在控制器的php文件中完成)。我認爲DTukans給出的解決方案很好。連接sql邏輯取決於它的PHP變量是否爲null。我會嘗試並返回結果。 – user1683645