php select语句依赖于现有变量
我正在尝试为我正在开发的一家小商店建立一个过滤系统。基本上,我正在根据变量列表计算结果。页面 products.php 如果没有查询字符串将显示所有产品。但是,如果存在变量,我希望它在必要时更改 select 语句。
但是,我在过滤时遇到问题。如果我对所有变量使用 AND 语句,它就不会正确过滤,OR 也不会。因此,如果我想要黑色 5 号鞋,无论颜色如何,它都会显示所有 5 号鞋。
有没有更好的方法来解决这个问题,因为它已经成为一个相当老的令人头疼的人了!
if ($queryString == NULL){
$query = "SELECT * FROM store_products
JOIN store_cat on store_products.cat=store_cat.cat_id
JOIN prod_sizes on store_products.prod_id=prod_sizes.product_id
JOIN prod_color on store_products.prod_id=prod_color.product_id
GROUP BY store_products.prod_id";
}else{
$query = "SELECT * FROM store_products
JOIN store_cat on store_products.cat=store_cat.cat_id
JOIN prod_sizes on store_products.prod_id=prod_sizes.product_id
JOIN prod_color on store_products.prod_id=prod_color.product_id
where store_products.sale='$sale' OR prod_color.color='$color' OR prod_sizes.size='$size' OR store_products.cat='$cat' GROUP BY store_products.prod_id";
}
示例变量字符串
products.php?sale=&cat_id=1&size=&color=Yellow
I am trying to set up a filter system for a small shop I am developing. Basically, I am working the results off a list of variables. the page, products.php if there is no querystring will show all products. However, if there is a variable present I want it to alter the select statement where necessary.
however, I am having problems filtering. If i use the AND statement for all variables it does not filter appropriately neither does the OR. So if i wanted black size 5 shoes it would show all size fives regardless of color.
Is there a better approach to take with this as is becoming a fair old head scratcher!
if ($queryString == NULL){
$query = "SELECT * FROM store_products
JOIN store_cat on store_products.cat=store_cat.cat_id
JOIN prod_sizes on store_products.prod_id=prod_sizes.product_id
JOIN prod_color on store_products.prod_id=prod_color.product_id
GROUP BY store_products.prod_id";
}else{
$query = "SELECT * FROM store_products
JOIN store_cat on store_products.cat=store_cat.cat_id
JOIN prod_sizes on store_products.prod_id=prod_sizes.product_id
JOIN prod_color on store_products.prod_id=prod_color.product_id
where store_products.sale='$sale' OR prod_color.color='$color' OR prod_sizes.size='$size' OR store_products.cat='$cat' GROUP BY store_products.prod_id";
}
example variable string
products.php?sale=&cat_id=1&size=&color=Yellow
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在运行查询之前尝试构建 WHERE 标准。
字符串:
products.php?sale=&cat_id=1&size=&color=Yellow
myfile.php
等等然后运行您的查询:
并且请记住先清理您的 $_GET 变量使用
mysql_real_escape_string
、mysqli
或PDO
来查询它们!Try building your WHERE criteria before running the query.
String:
products.php?sale=&cat_id=1&size=&color=Yellow
myfile.php
And so on then run your query:
And please remember to clean your $_GET variables prior to querying with them using
mysql_real_escape_string
,mysqli
orPDO
!然后你执行你的查询:)
Then you execute your Query :)