SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    361
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    IF-ELSE in WHERE clause of query

    Hi everyone,

    I need something like an IF-ELSE statement in the WHERE clause of my query.

    $q = "SELECT ...FROM ...WHERE name = '$name' if (isset($country)) echo && '$country' ";

    If the $country variable is set then the query needs to run with the value of that variable, otherwise the query runs without that value.


    Thanks in advance!!


    And Season's greetings/happy holidays to you all!!

  2. #2
    Barefoot on the Moon! silver trophy Force Flow's Avatar
    Join Date
    Jul 2003
    Location
    Northeastern USA
    Posts
    4,606
    Mentioned
    56 Post(s)
    Tagged
    1 Thread(s)
    You could append a condition to the query something like this:

    PHP Code:
    $q="SELECT * FROM `mytable` WHERE `name`='$name'";

    if(isset(
    $country))){
    $q.=" AND `country`='$country'";

    Visit The Blog | Follow On Twitter
    301tool 1.1.5 - URL redirector & shortener (PHP/MySQL)
    Can be hosted on and utilize your own domain

  3. #3
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    361
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks Force Flow,

    I'll give that a try!

  4. #4
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    361
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Okay, I've tried the code and it works - thanks. One problem though is that one of my queries contains a LIMIT at the end of the query:


    $q = "SELECT ...FROM ...WHERE name = '$name' LIMIT $somevariable ";


    All of the conditions need to be positioned before the LIMIT otherwise the query fails. Do you know what I can do in this situation?


    Thank you.

  5. #5
    Programming Team silver trophybronze trophy
    Mittineague's Avatar
    Join Date
    Jul 2005
    Location
    West Springfield, Massachusetts
    Posts
    17,156
    Mentioned
    190 Post(s)
    Tagged
    2 Thread(s)
    Couldn't you simply append it to the $q string before you use it?

  6. #6
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    361
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi all,

    it's working, thank you.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •