过滤产品价格并排序 Asc Desc PHP MYSQLI.



希望你永远关心! 有人问我:

  1. 如果我按表单价格最小到最大过滤产品,可以查看已经确定

  2. 在步骤过滤器(第 1 号(和过滤器 ASC 之后,DESC 条件为什么我的视图页面是"为 foreach(( 提供的参数无效",为什么它会???

.

<?php 
include("config.php");
$all_brand=$db->query("SELECT distinct brand FROM `products` WHERE category_id = '1' GROUP BY brand");
// Filter query
$sql= "SELECT distinct * FROM `products` WHERE category_id = '1'";
if(isset($_GET['brand']) && $_GET['brand']!="") :
$sql.=" AND brand IN ('".implode("','",$_GET['brand'])."')";
endif;
if(isset($_GET['sort_price']) && $_GET['sort_price']!="") :
if($_GET['sort_price']=='price-asc-rank') :
$sql.=" ORDER BY price ASC";
elseif($_GET['sort_price']=='price-desc-rank') :
$sql.=" ORDER BY price DESC";
endif;
endif;
// filter by input price
if(isset($_GET['min']) && $_GET['min']!="") :
$sql.="AND price >= '".$_GET['min']."' ";
endif;
if(isset($_GET['max']) && $_GET['max']!="") :
$sql.="AND price <= '".$_GET['max']."' ";
endif;
$all_product=$db->query($sql);
?>

和我的表格:

*******filter ASC and DESC **********
<div class="panel list">                  
<div class="col-sm-2">
<select name="sort_price" class="sort_rang" id="sort">
<option value="">Paling baru</option>
<option <?=(isset($_GET['sort_price'])&&($_GET['sort_price']=='price-asc-rank')? 'selected="selected"' : '' )?>  value="price-asc-rank">Harga:Rendah ke tinggi </option>
<option <?=(isset($_GET['sort_price'])&&($_GET['sort_price']=='price-desc-rank') ? 'selected="selected"' : '' )?>  value="price-desc-rank">Harga:Tinggi ke rendah</option>
</select>
</div>
</div>
<!-- filter price -->
<div class="sidebar-row">
<h4>RENTANG HARGA</h4>
<input type="text" name="min" id="min" placeholder=" Mulai dari harga" onkeypress="return AllowOnlyNumbers(event);" value="<?php echo isset($_GET['min']) ? $_GET['min'] : ''; ?>"> <br>
<br>
<input type="text" name="max" id="max" placeholder=" Sampai dgn harga" onkeypress="return AllowOnlyNumbers(event);" value="<?php echo isset($_GET['max']) ? $_GET['max'] : ''; ?>"> <br>
<br>
<input type="submit" class="sort_rang" value="Tampilkan">
</div> 

您不能将价格放在ORDER之后WHERE

include("config.php");
$all_brand=$db->query("SELECT distinct brand FROM `products` WHERE category_id = '1' GROUP BY brand");
// Filter query
$sql= "SELECT distinct * FROM `products` WHERE category_id = '1'";
if(isset($_GET['brand']) && $_GET['brand']!="")
$sql.=" AND brand IN ('".implode("','",$_GET['brand'])."')";
// filter by input price
if(isset($_GET['min']) && $_GET['min']!="")
$sql.="AND price >= '".$_GET['min']."' ";
if(isset($_GET['max']) && $_GET['max']!="")
$sql.="AND price <= '".$_GET['max']."' ";
if(isset($_GET['sort_price']) && $_GET['sort_price']!="") :
if($_GET['sort_price']=='price-asc-rank')
$sql.=" ORDER BY price ASC";
elseif($_GET['sort_price']=='price-desc-rank')
$sql.=" ORDER BY price DESC";
endif;

$all_product=$db->query($sql);

顺便说一句:您的代码容易受到SQL注入的攻击。这很糟糕,了解更多:http://bobby-tables.com/php

最新更新