Jump to content

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


imgrooot

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.