Make MySQL query meet multiple requirements

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
princeofvegas
Forum Newbie
Posts: 11
Joined: Wed Jun 30, 2010 1:21 am

Make MySQL query meet multiple requirements

Post by princeofvegas »

I have had a heck of a time figuring this out and it is driving me crazy!! lol. I am trying to make an SQL query meet several requirements from the table before the results are displayed. Here is the statement I am working with:

Code: Select all

$searchresult = mysql_query("SELECT * FROM coupons WHERE category_id='5' AND coupon_zip='89118'");
I want it to only pull rows from the database where both the category ID match AND the coupon ZIP match. Unfortunately no matter how many times I try it it still provides me with rows that have either one or both of the requirements. Am I doing something wrong? Any help would be appreciated.
rahulzatakia
Forum Commoner
Posts: 59
Joined: Fri Feb 05, 2010 12:01 am
Location: Ahmedabad

Re: Make MySQL query meet multiple requirements

Post by rahulzatakia »

Hi, I have tried your query and there is no problem in it. Its working fine with me. If you still have any error then let me know with more code as to find out where is the exact problem.
princeofvegas
Forum Newbie
Posts: 11
Joined: Wed Jun 30, 2010 1:21 am

Re: Make MySQL query meet multiple requirements

Post by princeofvegas »

I just tried breaking it down and it works perfectly when I run the query like that.. However, I just noticed that the problem starts and I get unexpected results when I run the query like this:

Code: Select all

$searchresult = mysql_query("SELECT * FROM coupons WHERE category_id='5' OR category_id='6' AND coupon_zip='89118' or coupon_zip='91361'");
I dont know if the OR statements are confusing it and if so is there a more proper way to do it?
User avatar
Jade
Forum Regular
Posts: 908
Joined: Sun Dec 29, 2002 5:40 pm
Location: VA

Re: Make MySQL query meet multiple requirements

Post by Jade »

You need to put parenthesis around your logic.

Code: Select all

$searchresult = mysql_query("SELECT * FROM coupons WHERE (category_id='5' OR category_id='6') AND (coupon_zip='89118' or coupon_zip='91361)'");
princeofvegas
Forum Newbie
Posts: 11
Joined: Wed Jun 30, 2010 1:21 am

Re: Make MySQL query meet multiple requirements

Post by princeofvegas »

Hello thank you for you help with this. That worked perfectly. I also found that this line worked as well:

Code: Select all

$searchresult = mysql_query("SELECT * FROM coupons WHERE category_id IN (5, 6) AND coupon_zip IN (89118, 91361)");
Finally hours of headache are gone. :D
Post Reply