1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Query with a multiple select-box

Discussion in 'Databases' started by fgatlin, Feb 25, 2015.

  1. #1
    Trying to query MySQL for search results.

    MySQL Query:
    if(isset($_POST['skill']) and $_POST['skill'] != '') {
      $skills = $_POST['skill'];
      if (count($skills) > 0) {
        // loop through the array
        for ($i=0;$i<count($skills);$i++) {
          $sql .= " and (primary_skills.primary_skill IN ('".$skills[$i]."') OR primary_skills.primary_skill IN ('".$skills[$i]."')) ";
        }
      }
    }
    Code (markup):
    My var_dump for the query is showing:
    and (primary_skills.primary_skill IN ('MAFS.1.G.1.2') OR primary_skills.primary_skill IN ('MAFS.1.G.1.2'))  and (primary_skills.primary_skill IN ('MAFS.1.G.1.3') OR primary_skills.primary_skill IN ('MAFS.1.G.1.3'))
    Code (markup):
    It works like a charm when only one selection from the multiple select-box is made, but when two or more is made, I get multiple AND & OR in the query.
     
    fgatlin, Feb 25, 2015 IP
  2. Profitup

    Profitup Greenhorn

    Messages:
    50
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    13
    #2
    That's right, because you have "AND & OR " in one string in cycle. I don't know your goal, but it seems you don't need "OR". Why do you use it?
     
    Profitup, Feb 25, 2015 IP
  3. fgatlin

    fgatlin Greenhorn

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    21
    #3
    I have it working now:

    if(isset($_POST['skill']) and $_POST['skill'] != '') {
      $skills = $_POST['skill'];
      $sql .= " and (primary_skills.primary_skill = '".$skills[1]."'";
      if (count($skills) > 0) {
        // loop through the array
        for ($i=0;$i<count($skills);$i++) {
          $sql .=" OR primary_skills.primary_skill ='".$skills[$i]."' ";
        }
      }
    }
        $sql .= ")";
    Code (markup):
     
    fgatlin, Feb 25, 2015 IP