我有2个变量来定义查询的价格范围。我试图解决的问题是,当这些未设置时,我想要显示所有行(如果下边界为空,则为1,如果上边界为空,则为max(price))。
我尝试使用ifnull
,但没有成功。
$priceFrom = $_POST['priceFrom'];
$priceTo = $_POST['priceTo'];
if(is_null($priceFrom) || is_null($priceTo)){
$priceFrom = 0;
$priceTo = 0;
}
$mass = array();
foreach($data as $current){
$sql = "SELECT p.price,
p.type,
p.area,
p.floor,
p.construction,
p.id as propertyID,
CONCAT(u.name, ' ',u.family) as bname,
p.type as ptype,
n.name as neighborhoodName,
CONCAT(o.name,' ',o.surname,' ',o.family) as fullName
FROM `property` p
LEFT JOIN `neighbour` n ON p.neighbour = n.id
RIGHT JOIN `owners` o ON p.owner = o.id
LEFT JOIN users u ON p.broker = u.id
WHERE `neighbour`= '$current'
AND `price` BETWEEN ifnull('$priceFrom', '1') AND ifnull('$priceTo','2000000')
";}
答案 0 :(得分:1)
SQL INJECTION
^请谷歌那个!您的代码 严重易受攻击! 您的数据可能被盗或被删除...
您必须至少使用mysqli_real_escape_string()
更好的是take proper countermeasures to SQL injection并使用准备好的语句和参数化查询! (如下面的代码所示)
我认为最好的方法是通过根据变量的值更改查询来处理逻辑:
$sql = "SELECT p.price,
p.type,
p.area,
p.floor,
p.construction,
p.id as propertyID,
CONCAT(u.name, ' ',u.family) as bname,
p.type as ptype,
n.name as neighborhoodName,
CONCAT(o.name,' ',o.surname,' ',o.family) as fullName
FROM `property` p
LEFT JOIN `neighbour` n ON p.neighbour = n.id
RIGHT JOIN `owners` o ON p.owner = o.id
LEFT JOIN users u ON p.broker = u.id
WHERE `neighbour`= :current "; //note: ending white space is recommended
//lower boundary clause -- if variable null - no restriction
if(!is_null($priceFrom){
sql = sql . " AND `price` >= :priceFrom "; // note: whitespace at end and beginning recommended
}
//upper boundary -- better than to set it to an arbitrary "high" value
if(!is_null($priceTo)){
sql = sql . " AND `price` <= :priceTo "; // note: whitespace at end and beginning recommended
}
这种方法允许任何较高的价值:如果存在严重的通货膨胀,不同的货币,或突然代码将被用于出售房屋,并且将会有价格> 1的产品。 200000,你不需要出去改变很多代码就可以显示......
当执行查询时,需要绑定参数:
$stmt = $dbConnection->prepare(sql);
$stmt->bind_param('current', $current);
if(!is_null($priceFrom)){
$stmt->bind_param('priceFrom', $priceFrom);
}
if(!is_null($priceTo)){
$stmt->bind_param('priceTo', $priceTo);
}
//execute and process in same way
$stmt->execute();
另请注意:您的代码似乎是在循环中发出查询。这是不良做法。如果你循环的数据来了
JOIN
IN
子句使用一个查询获取所有数据。在大多数情况下,这通常可以在组织和维护代码和结果方面提供更多帮助。