duanjiu4498 2016-08-02 04:29
浏览 44

我可以改变mysql查询取决于用户输入,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. 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>
  • 写回答

1条回答 默认 最新

  • dqa35710 2016-08-02 09:39
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)