dpfqy5976 2012-10-12 15:05 采纳率: 100%
浏览 30
已采纳

使用下拉框过滤MYSQL数据

I have populated an html page with a table from the database. I want to add dropdown boxes at the top that can filter out unnecessary data. How would I go about sending this information to the database to make a query so that I can filter out data with multiple variables?

For example, I have 5 categories, A, B, C, D, and E. I have used PHP code to populate the boxes with the possible values/entries for A, B, C, D, and E. I've also added a "NULL entry" in case the user does not want to include this column as part of the filter.

So right now as it stands, for the respective columns we can have:

Apple, always, as, amazing, as, almonds, NULL.
Belly, boosts, bad, NULL.
Candy, can, create, NULL.
Dandy, does, do, don't, NULL.
Elements, exist, NULL.

How would I go about sending the information to the database when the variables are indefinite? They may or may not be set.

I figured I'd start by seeing if the variables were set in the first place by using the isset(), but how would I proceed from there? It seems like a lot of 'if' statements. All I need to do is to change the query based on the values of the variables the user enters. But I don't see an easy way of doing that.

I'll simply be adding "WHERE A = this AND B = that AND C = thisthat AND .." to the end of the query but what if one or more or all of those entries are null?

Thanks a lot for any help.

  • 写回答

1条回答 默认 最新

  • dqef7931 2012-10-12 15:11
    关注

    You can easily construct your WHERE query as follows

    $where = array();
    
    if ($A != '')
    { 
        $where[] = 'A = "' . $A . '"';
    }
    
    if ($B != '')
    { 
        $where[] = 'B = "' . $B . '"';
    }
    
    if ($C != '')
    { 
        $where[] = 'C = "' . $C . '"';
    }
    
    if ($D != '')
    { 
        $where[] = 'D = "' . $D . '"';
    }
    
    if ($E != '')
    { 
        $where[] = 'E = "' . $E . '"';
    }
    
    // Now get the $where
    $final_where = '';
    if (count($where) > 0)
    {
        $final_where = implode(' AND ', $where);
    }
    
    // $final_where will contain
    // A = 'ab' AND B = 'cd' etc.
    

    NOTE Please make sure to sanitize your input. So for instance you need to add a check for $A that it contains the values that you expect it to contain. Anything else must be discarded. You can use the in_array for instance like so:

    $a_array = array('first value', 'second value', 'third value');
    if (in_array($A, $a_array))
    {
        // Valid choice - we can use it
    }
    else 
    {
        // Not valid set $A to null
        $A = '';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器