How to write an IF statement inside a MySQL query?

Discussion in 'MySQL' started by MajHate, Nov 14, 2013.

  1. #1
    Hello,

    I'm creating a php/MySQL script to do a simple search. I have a table in MySQL called "classes" and it has the following fields: "class, date, time". I've figured out how to search in a certain date range, however in conjunction with that, I need to be able to search for 'class' and 'time'. For the 'time' field I give the user 4 options to search from: "Morning, Afternoon, Evening, All". I also have drop down list of for the classes, for example: "Class 1, Class 2, Class 3, All Classes". Here is what I have so far:

    $select = "select * from classes WHERE UTC>='$from' && UTC<='$to' ORDER BY date ASC"


    So how do I incorporate searching for 'class' and 'time' into this search? It seems like the logical thing to do would be to put a IF statement into the MySQL query, but is that possible? Please help!

    Thank you!
     
    Last edited: Nov 14, 2013
    MajHate, Nov 14, 2013 IP
  2. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #2
    Can't you just do "SELECT * FROM classes WHERE (UTC>='$from' AND UTC<='$to') AND class = '$class' AND time = '$time' ORDER BY date ASC"?

    Would of course mean that you'll need to make all the search fields required.
     
    PoPSiCLe, Nov 15, 2013 IP