douren1891 2012-04-30 21:31
浏览 17
已采纳

如何构建动态mysql查询以适应所有用户

I need your help with my website search functionality. I'm developing a members area wherein users can search other registered users based on certain criteria, or combination of criteria.

My problem now is how to build a dynamic mysql query to suit the need of each combination of search criteria, where the number of criteria is variable.

Normally, I can write with a pre-determined set of criteria using

   WHERE param1 = '$param1'
   AND param2 = '$param2'
   AND param3 = '$param3'

How do I solve this problem?

  • 写回答

7条回答 默认 最新

  • donglei1699 2012-04-30 21:45
    关注

    If the issue is that you don't know which of the criteria the user will pick, but want to return results for "blank" criteria, you can use the following:

    $criteria_1 = $_POST['criteria_1'];
    $criteria_2 = $_POST['criteria_2'];
    $criteria_3 = $_POST['criteria_3'];
    
    if(!$criteria_1 && !$criteria_2 && !$criteria_1) {
    
         echo "You must select at least one criteria!";
    
    } else {
    
       // Run query mentioned below and return results.       
    
    } 
    

    THe query would then look like:

    SELECT * from mytable
    WHERE
    (criteria1 = '$criteria_1' OR '$criteria_1' = '') AND
    (criteria2 = '$criteria_2' OR '$criteria_2' = '') AND
    (criteria3 = '$criteria_3' OR '$criteria_3' = '')
    

    This will treat any blank (non-selected) parameters as blank and ignore them. Be aware that with the above, if no criteria are given, it will return all results.

    Another way to write the above is:

    SELECT * from mytable
    WHERE
    criteria1 IN ('$criteria_1', '') AND
    criteria2 IN ('$criteria_2', '') AND
    criteria3 IN ('$criteria_3', '')
    

    Again, allowing for no entry at all to return all criteria1 results.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算