imgrooot Posted August 7, 2017 Share Posted August 7, 2017 I have a query below where I want to search a table to find the top row with 1 or 2 empty positions. But it never returns the correct "referral_id". If I remove the "ref_user_1" and "ref_user_2" conditions from the query, then of course it will return the correct referral id. But those conditions are important for me to have. Is having "AND" and "OR" conditions in the same query against the rules? If so what's the solution for this problem? $find_sponsor = $db->prepare("SELECT * FROM referrals WHERE referred_by = :referred_by AND ref_user_1 = :ref_user_1 OR ref_user_2 = :ref_user_2 ORDER BY referral_id ASC LIMIT 1"); $find_sponsor->bindValue(':referred_by', 2); $find_sponsor->bindValue(':ref_user_1', 0); $find_sponsor->bindValue(':ref_user_2', 0); $find_sponsor->execute(); $result_sponsor = $find_sponsor->fetchAll(PDO::FETCH_ASSOC); if(count($result_sponsor) > 0) { foreach($result_sponsor as $row) { $get_referral_id = $row['referral_id']; $get_ref_1 = $row['ref_user_1']; $get_ref_2 = $row['ref_user_2']; } echo $get_referral_id; // this always returns the wrong referral id } // Table referral_id referred_by ref_user_1 ref_user_2 1 2 20 21 2 2 23 24 3 2 25 0 4 2 0 0 As per my table above, what would my new query look like if I want to retrieve #3 as my referral id? Quote Link to comment Share on other sites More sharing options...
Solution Barand Posted August 7, 2017 Solution Share Posted August 7, 2017 It OK to have AND and OR in a query but it is always better to use parentheses when doing so. EG Instead of ... WHERE A AND B OR C use ... WHERE A AND (B OR C) This removes any ambiguity about whether you meant (A AND B) OR C Quote Link to comment Share on other sites More sharing options...
imgrooot Posted August 7, 2017 Author Share Posted August 7, 2017 It OK to have AND and OR in a query but it is always better to use parentheses when doing so. EG Instead of ... WHERE A AND B OR C use ... WHERE A AND (B OR C) This removes any ambiguity about whether you meant (A AND B) OR C Well that was simple. it did the trick. Thanks. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.