Jump to content

I am having issue with selecting a certain id with this query. Need help.


imgrooot
Go to solution Solved by Barand,

Recommended Posts

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?

 

 

 

 

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.