A mysql query I need help with -- can you figure it out?

Discussion in 'PHP' started by phantom, Oct 24, 2007.

  1. #1
    I have a list of products and I am trying to build a search query for. The product row has a field called 'approved' which is set to '1' if approved or '0' if not approved.

    I only want to search approved products set to '1'.

    Here is my code so far:


    SELECT * FROM archive WHERE  approved='1' and  products LIKE '%$search%' or description like '%$search%' LIMIT $offset, $entries_per_page ")
      or die("Selecting that crap failed ");
    Code (markup):
    $search is of course a variable.

    Any way so far this code selects all products that match $search despite what approved is set at.

    Can someone help me formulate this query to only select the ones that match $search where approved='1' ?

    Thanks in advance!
     
    phantom, Oct 24, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    Try putting all "OR"s between parenthesis.

    
    SELECT *
    FROM
        archive
    WHERE
        approved = 1 AND (
        products LIKE '%$search%' OR
        description LIKE '%$search%'
    )
    LIMIT
        $offset, $entries_per_page
    
    Code (sql):
     
    nico_swd, Oct 24, 2007 IP
  3. benajnim

    benajnim Peon

    Messages:
    20
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    The issue may be related to the case of the text in the name & description fields and your search string.

    You could try using ilike, or make sure everything is always upper or always lower:

    $search = strtolower($search)

    lower(name) like '%$search%'
     
    benajnim, Oct 24, 2007 IP
  4. benajnim

    benajnim Peon

    Messages:
    20
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Good call.

     
    benajnim, Oct 24, 2007 IP
  5. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #5
    SELECT queries are case-insensitive by default.
     
    nico_swd, Oct 24, 2007 IP
  6. phantom

    phantom Well-Known Member

    Messages:
    1,509
    Likes Received:
    32
    Best Answers:
    0
    Trophy Points:
    140
    #6
    nico........you are the bomb!

    It works perfectly thanks a million!
     
    phantom, Oct 24, 2007 IP