skip to Main Content

I am having a form which contains some field(language,Datefrom,Dateto,Status).There is a submit button.I want to fetch the data based on the value filled on these field.My query to ignore the field which is not filled.How can i write the query.

Select * from tbldep where (language='$language') AND ( Date between '$Datefrom' AND '$Dateto')AND (status='$status')

My query to ignore the value which is not filled. Suppose user has not filled the value of date in DateFrom field in that case query should fetch the all record which are less than DateTo value.

2

Answers


  1. IFNULL. If there is no date, replace the null with a default that will get the data you want.

    Select * 
      from tbldep 
      where (language='$language') 
        AND ( Date between IFNULL('$Datefrom', '1900/01/01') AND '$Dateto')
        AND (status='$status')
    
    Login or Signup to reply.
  2. You can use boolean logic – although that’s a bit lengthy to express:

    select * 
    from tbldep 
    where (:lang    is null or language = :lang) 
      and (:dt_from is null or date    >= :dt_from)
      and (:dt_to   is null or date    <= :dt_to)
      and (:stat    is null or status   = :stat)
    

    Note that this uses bind parameters (with the : prefix) instead of string concatenation to build the query (which is unreliable and unsafe).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search