简体   繁体   English

我可以改变mysql查询取决于用户输入,php?

[英]Can I alter the mysql query depends on user entry, php?

I have a situation is that the query depends on user entry. 我有一种情况是查询取决于用户输入。 If user enter toy, then query will have some OR, if user enter TV, then the query will slightly different. 如果用户输入玩具,那么查询将有一些OR,如果用户输入TV,则查询会略有不同。 The simple way to do that is like below. 这样做的简单方法如下。 However, when I have a lot of different products, what is the best way to do it? 但是,当我有很多不同的产品时,最好的方法是什么? I want to create an array to include all products and use if condition inside the query, but if this doable or any better way? 我想创建一个数组来包含所有产品并在查询中使用if条件,但是如果这样做或者更好的方法? appreciate. 欣赏。

 <?php if ($toy){ $sql = $wpdb->get_results( $wpdb->prepare(" SELECT DISTINCT product FROM dis WHERE cat IN (%s, %s, %s) AND (val !=%s AND mark='price') or (val !=%s AND mark='country') or (val !=%s AND mark='shipping') or (val !=%s AND mark='quality') or (val !=%s AND mark='frequency') or (val !=%s AND mark='duration') ",$a,$b,$c,$d,$e,$f)); } if($tv){ $sql = $wpdb->get_results( $wpdb->prepare(" SELECT DISTINCT product FROM dis WHERE cat IN (%s, %s, %s) AND (val !=%s AND mark='price') or (val !=%s AND mark='country') or (val !=%s AND mark='shipping') ",$a,$b,$c,$d,$e,$f)); } /*I have a lot*/ ?> 

You can either store the mapping (between product types and their parameters) inside PHP code or inside a database table. 您可以将映射(在产品类型及其参数之间)存储在PHP代码中或数据库表中。 In the case you store it in PHP: 在您将其存储在PHP中的情况下:

$mapping = Array(
  'toy' => Array('country', 'shipping', 'quality', 'frequency', 'duration'),
  'tv'  => Array('country', 'shipping')
);

$query = 'SELECT DISTINCT product FROM dis WHERE cat IN (';
foreach($category as $k=>$v) $category[$k] = '"'.mysql_real_escape_string($v).'"';
$query .= implode(',', $category);
$query .= ') AND ((val !="'.mysql_real_escape_string($price).'" AND mark="price") ';
foreach($mapping[$kind] as $v) 
  $query .= ' or (val !="'.mysql_real_escape_string($parameter[$v]).'" AND mark="'.$v.'")';
$query .= ')';
$sql = $wpdb->get_results($query);

Looking at your SQL I can presume that you have one big table for all products - and each product is represented with many rows, one row for each of the parameters of the product. 看看你的SQL,我可以假设你有一个适用于所有产品的大表 - 每个产品都有很多行,每行产品都有一行。 This is a BAD design ! 这是一个不好的设计 You'd better use 2 separate tables - one will contain only the products (only 1 row for each product) and the other table will contain product parameters (using ONE-to-MANY relationship) - each parameter on a distinct row. 您最好使用2个单独的表 - 一个仅包含产品(每个产品只有一行),另一个表将包含产品参数(使用ONE-to-MANY关系) - 每个参数位于不同的行上。

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

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