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. 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? 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*/
?>
</div>
You can either store the mapping (between product types and their parameters) inside PHP code or inside a database table. In the case you store it in 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. 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.