2016-06-10 114 views
0

我有一個下拉框,用戶可以選擇一個位置。然後,有一個文本框,他們可以輸入最大的租賃價格(在這個例子中,將會有更多的選擇,但只保留簡單的東西)。然後這將轉到results.php頁面,並使用$ _GET數組提取值並查詢數據庫

如果兩個字段都是完整的,這可以正常工作,但如果他們只想按位置進行搜索並保留租金字段空白它不起作用,然後顯示results.php?loc = york & rent =在URL中,然後如我使用AND函數顯示沒有結果?

我對PHP非常陌生,非常感謝任何能指引我正確方向的人或者在谷歌搜索的正確術語?

<?php 
$location = $_GET['loc']; 
$rent=$_GET['rent']; 

$result = $mysqli->query("SELECT * FROM dbc_posts WHERE '$location'=city &&'$rent'>rent_price ORDER BY ID ASC"); 

?> 
+0

由於某種原因,它始終缺少開始位關閉我的問題,應該閱讀,我有一個下降....... –

+0

你應該使用準備好的陳述.. –

+1

'如果($ rent){添加條件查詢}' –

回答

0

您既可以創建2個查詢,也可以創建2個查詢,或者只包含一些變量。

$rent = $_GET['rent']; 
$rent_options = ""; 
if(isset($rent)) //add condition 
{ 
     $rent_options .= "&& \'rent\'>rent_price"; 
} 
$mysqli->query("SELECT * FROM dbc_posts WHERE '$location'=city".$rent_options." ORDER BY ID ASC"); 

這樣,假設他們選擇租用選項,它將被添加到查詢中。如果不是,它將只是空白而被忽略。

+0

我想可能是它不會被忽略 –

+0

感謝您的所有幫助,但這似乎是我最好的選擇,可以輕鬆添加更多選項,謝謝 –

1

試試這個

<?php 

     // you can check for sql injection 
     $location = $_GET['loc']; 
     $rent=$_GET['rent']; 

     // check if $_GET['rent'] is provided and has a value 
     if(isset($_GET['rent']) && $_GET['rent']) { 

     $result = $mysqli->query("SELECT * FROM dbc_posts WHERE city='$location' AND rent_price < '$rent' ORDER BY ID ASC"); 

     // do remaining stuff 

     } else { 

     // rent is not provided 
     $result = $mysqli->query("SELECT * FROM dbc_posts WHERE city='$location' ORDER BY ID ASC"); 

     // do other stuff 

     } 



    ?> 
0

如果$租金是空的,你必須先查詢數據庫之前檢查它。

if(!empty($rent)) 
{ 
    $result = $mysqli->query("SELECT * FROM dbc_posts WHERE city='$location' and rent_price<'$rent' ORDER BY ID ASC"); 
} else { 
    $result = $mysqli->query("SELECT * FROM dbc_posts WHERE city='$location' ORDER BY ID ASC"); 
}