2016-06-10 119 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"); 
}