简体   繁体   English

SQL:根据发布的值更新SQL查询

[英]Sql : Update sql query on the basis of posted values

i am doing a query on the basis of posted values for eg. 我正在基于例如发布值进行查询。 following is the query 以下是查询

$query= mysqli_query($connect,
                "SELECT * FROM residential  WHERE type='$type' AND unit_type='$unit_type' "
                . "AND  price BETWEEN '$min_price' AND '$max_price' "
                . " AND bedrooms BETWEEN '$min_bedrooms' AND '$max_bedrooms'"); 

now $unit_type , $min_price etc are coming from $_POST array , my problem is that if i don't receive any of the used values ($type ,$max_bedrooms, $min_bedrooms etc ) in query, then query does not work. 现在$unit_type , $min_price etc are coming from $_POST array ,我的问题是,如果我在查询中未收到任何使用的值($type ,$max_bedrooms, $min_bedrooms etc ) ,则查询将不起作用。 my question is how do i update the query on the basis of only posted values . 我的问题是如何仅根据发布的值更新查询。

Use a $query variable and change it by your post values 使用$ query变量并根据您的帖子值进行更改

$query= "SELECT * FROM residential  WHERE 1=1 "; 
if($type!=""){
 $query.=" AND  type='$type'";
}
if($unit_type!=""){
 $query.=" AND  unit_type='$unit_type'";
}
if(($min_price!="") && ($max_price!="")){
 $query.=" AND  price BETWEEN '$min_price' AND '$max_price' ";
}
if(($min_bedrooms!="") && ($max_bedrooms!="")){
 $query.=" AND bedrooms BETWEEN '$min_bedrooms' AND '$max_bedrooms'";
}
$result= mysqli_query($connect,$query);

you can (should) perform some validating before putting variables into query. 您可以(应该)在将变量放入查询之前执行一些验证。 There you can check if vars are sent (and valid types etc.) and if they are not, you can replace them with your default values. 您可以在此处检查是否发送了var(以及有效类型等),如果没有发送,则可以将其替换为默认值。

There is another way to do this, in your query you can use COALESCE() function where you specify default value if your value is not present ex.: COALESCE('$unit_type', 'coin'). 还有另一种方法,在查询中可以使用COALESCE()函数,如果不存在默认值,则可以在其中指定默认值,例如:COALESCE('$ unit_type','coin')。

As mentioned in comments, you should be aware of SQL injection. 如注释中所述,您应该了解SQL注入。 You can avoid it by strict validating&encoding sent variables or by using some prepared statements for composing sql queries (dibi, pdo ..). 您可以通过严格验证和编码发送的变量或使用一些准备好的语句来构成sql查询(dibi,pdo ..)来避免这种情况。

Hope it helps :) 希望能帮助到你 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM