2014-10-01 53 views
-2

我想創建一個將查詢數據庫表的搜索功能。使用php和mysql在數據庫中搜索

以下表單提交的搜索參數:

<form id="form_searchJobs" name="form1" method="post" action=""> 
    <label id="destinationLabel">Destination</label> <input name="destination_search" type="text" id="destination_search"/> <br/> 
    <label id="cargoLabel">Cargo</label> <input type="text" name="cargo_search" id="cargo_search"/> <br/> 
    <label id="deadlineLabel">Deadline</label> <input type="text" name="deadline_search" id="datepicker"/> <br/> 
    <input type="submit" name="search" id="search" class="button3" value="Search" onClick="showSearchedString()"/> 
    <a href="../Jobs.php" id="clearSearch" class="button3">Clear Search</a> 
</form> 

搜索功能應該讓你同時在每個單獨的文本框的或全部的搜索。

我有後續的數據庫查詢:

if (isset($_POST['destination_search']) || (isset($_POST['cargo_search']) || (isset($_POST['deadline_search'])))) { 
    $destination_search = $_POST['destination_search']; 
    $cargo_search = $_POST['cargo_search']; 
    $deadline_search = $_POST['deadline_search']; 
    $newDate = date("y-m-d", strtotime($deadline_search)); 
    $query = sprintf("SELECT * FROM jobs WHERE destination LIKE %s OR jobs.cargo LIKE %s OR RSVP_date LIKE %s ORDER BY destination ASC", GetSQLValueString("%" . $destination . "%", "text"),GetSQLValueString("%" . $deadline_search . "%", "text"),GetSQLValueString("%" . $newDate . "%", "text")); 
} 
else { 
$query = "SELECT * FROM jobs ORDER BY destination ASC"; 
} 

但這查詢顯示所有的結果,無論搜索項。我的查詢出了什麼問題,但是現在我不知道爲了同時從單個變量或全部變量中進​​行搜索?

+0

由於您在查詢中使用'OR',因此您必須修改目的地,貨物,截止日期的查詢,您將獲得所有結果 – justrohu 2014-10-01 09:23:34

+0

但是,如果我使用'AND'而不是'OR',則查詢需要所有要填寫的字段返回搜索結果。那麼我怎麼才能根據目的地,貨物,截止日期修改查詢? – user1825067 2014-10-01 10:00:21

回答

1

如果例如您destination_search包含文本,但你cargo_search和deadline_search不,你的輸出查詢會是這個樣子:

$where = []; 

if(isset($_POST['destination_search'])){ 
    $where[] = "`destination_search` LIKE '%" . mysql_real_escape_string($_POST['destination_search'] . "%'"; 
} 

if(isset($_POST['cargo_search'])){ 
    $where[] = "`cargo` LIKE '%" . mysql_real_escape_string($_POST['cargo_search']) . "%'"; 
} 

if(isset($_POST['deadline_search'])){ 
    $newDate = date("y-m-d", strtotime($_POST['deadline_search'])); 
    $where[] = "`RSVP_date` LIKE '%" . mysql_real_escape_string($_POST['deadline_search']) . "%'"; 
} 

$whereStatement = ""; 
if(count($where) > 0){ 
    $whereStatement = "WHERE " . implode(" AND ", $where); 
} 

$query = " 
    SELECT * 
    FROM  `jobs` 
    " . $whereStatement . " 
    ORDER BY `destination` ASC"; 

這是否更好地工作?

+0

如果我使用AND而不是OR,那麼查詢在所有字段未被填充時失敗?或者它沒有返回任何東西,因爲查詢需要填寫的其他兩個字段 – user1825067 2014-10-01 09:49:24

+0

我改變了我的答案,這是否更好? :) – 2014-10-01 11:09:55

+0

是的,這是完美的!謝謝 :-) – user1825067 2014-10-01 12:13:48