dongshai2022 2011-12-07 21:33 采纳率: 100%
浏览 361
已采纳

如果字段为空,则返回所有结果

I'm working at a search script at the moment, but I have a little problem. I'm using the following query:

mysql_query("SELECT * FROM boeken WHERE 
             titel LIKE '%".$titel."%' AND 
             categorie_id = '".$categorie."' AND 
             auteurs LIKE '%".$auteurs."%' AND 
             jaar_copyright = '".$jaar_copyright."' 
             AND ontwerp_groep = '".$ontwerp_groep."'");

For example, when I search for 'categorie_id' = '5', and leave the other fiels empty, I want to get every row that has categorie_id = 5. No matter what the other fields are.

What it does is the following: I get every row that has categorie_id = 5, but where the title is empty, where the 'jaar_copyright' is empty, etc. etc.

How can I fix this the way I want?

  • 写回答

5条回答 默认 最新

  • duanruoyu6675 2011-12-08 16:23
    关注
    <?php
    
        $query = "SELECT * FROM boeken WHERE";
        $n = 0;
        $makeAnd = "";
    
        foreach($_POST as $key=>$value){
            if($value != '' && $value != 'submit'){
                if($n != 0){$makeAnd = " AND";}
                if(!is_numeric($value)){
                $query .= "$makeAnd `$key` LIKE '%$value%'";
            } else {
                $query .= "$makeAnd `$key` = '$value'";
            }
                $n++;
            }
    
        }
    
        print $query;
    
    
    ?>
    

    In this way you can filter out empty values. If other values are posted to $_POST make sure to filter them out in the "if($value !=" part.

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

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题