PHP and MySQL optional WHERE conditions

后端 未结 4 2109
心在旅途
心在旅途 2021-01-29 09:59

I have the following problem: I want to let a user apply filters to a DB search. I have three filters, A, B and C. All of them can be \"empty\", as in, the user doesn\'t care a

4条回答
  •  难免孤独
    2021-01-29 10:01

    Try doing something like this:

    if @param1 is not null
       select * from table1 where col1 = @param1
    else
       select * from table1 where col2 = @param2
    

    This can be rewritten:

    select * from table1
    where (@param1 is null or col1 = @param1)
      and (@param2 is null or col2 = @param2)
    

    Got the idea from Baron Schwartz's blog: https://www.xaprb.com/blog/2005/12/11/optional-parameters-in-the-where-clause/

提交回复
热议问题