SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Guru
    Join Date
    Dec 2005
    Posts
    964
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    if/else inside sql query?!

    How do I put and if/else statement inside an sql query?

    PHP Code:
    if($hcpgroup == 0){
        .
    "WHERE cu.clubid = '$clubid' ".
    } else {
        .
    "WHERE cu.clubid = '$clubid' AND u.h_index >= '$hcpgroup_start' AND u.h_index <= '$hcpgroup_end' "
    }
    .
    "ORDER BY ecl.st_total ASC") or exit(mysql_error()); 
    Can it be done?

    Tnaks in advance...

  2. #2
    SitePoint Evangelist Waffles's Avatar
    Join Date
    Nov 2005
    Posts
    435
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:

    $query 
    "SELECT * FROM table";

    if(
    $hcpgroup == 0){

       
    $query.= " WHERE cu.clubid = '$clubid' ".

    } else {

        
    $query.= " WHERE cu.clubid = '$clubid' AND u.h_index >= '$hcpgroup_start' AND u.h_index <= '$hcpgroup_end' "

    }

    $query.=" ORDER BY ecl.st_total ASC";

    //$query= SELECT * FROM table WHERE cu.clubid = '$clubid' ORDER BY ecl.st_total ASC

    $result=myql_query($query);
    // etc 
    should do it. essentially just concating parts of the query together.

  3. #3
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Or, to cut things down a bit:

    Or, even more:
    PHP Code:
    $Query "SELECT column, anothercolumn FROM table WHERE cu.clubid = '{$clubid}'";
    if(
    $hcpgroup != 0){
        
    $Query.= " AND u.h_index >= '{$hcpgroup_start}' AND u.h_index <= '{$hcpgroup_end}'";
    }
    $Query.=" ORDER BY ecl.st_total ASC"
    PHP Code:
    $Query SPrintF("SELECT column, anothercolumn FROM table WHERE cu.clubid = '%s' %s  ORDER BY ecl.st_total ASC"$clubid, ($hcpgroup 0) ? "AND u.h_index >= '{$hcpgroup_start}' AND u.h_index <= '{$hcpgroup_end}'" ''); 
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  4. #4
    SitePoint Guru
    Join Date
    Dec 2005
    Posts
    964
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by arkinstall View Post
    Or, to cut things down a bit:

    Or, even more:
    PHP Code:
    $Query "SELECT column, anothercolumn FROM table WHERE cu.clubid = '{$clubid}'";
    if(
    $hcpgroup != 0){
        
    $Query.= " AND u.h_index >= '{$hcpgroup_start}' AND u.h_index <= '{$hcpgroup_end}'";
    }
    $Query.=" ORDER BY ecl.st_total ASC"
    Thanks to both... Perfect solutions ;-)


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
  •