0

I am trying to obtain results for a given member where status is pending or accepted doing the below:

$status1 = "Pending";
$status2 = "Attended";
$query = $conn->prepare('SELECT * FROM members WHERE member_id=:mID AND status=:status1 OR status=:status2');
$query->execute(array(':mID' => $mID,':status1' => $status1, ':status2' => $status2));
if ($query->rowCount() > 0) {
   //start to create my table    
   while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
   //create variable, loop through and fill the table etc
   }
}else{
   echo "something";
}

This displays data - however, it even obtains results not specific to the member id (mID). Meaning other members data too!

I'm clearly missing something and or my query is wrong but struggling to find anything..

Any help appreciated.

3
  • 1
    Group the or statements. or use an in like WHERE member_id=:mID AND status in (:status1, :status2) Commented Aug 1, 2018 at 19:55
  • 1
    If this is your use case, note there isn't really a reason to use prepared statements at all. It's just as safe to do SELECT * FROM members WHERE member_id=:mID AND status='Pending' OR status='Attended', which would get rid of the execute line of code, and shorten prepare to query. Keeping the prepare() does have a negative consequence however, and that is that the query will hit your database 2 times instead of just once (This is a probably a micro-optimization unless you do this frequently). The only time prepare is needed, is if there is user input going to the database. Commented Aug 1, 2018 at 20:20
  • @GrumpyCrouton - noted, thanks for the advise. Commented Aug 1, 2018 at 20:34

1 Answer 1

6

You need to look at operator precedence for your database. You're doing this:

SELECT * FROM members WHERE member_id = :mID AND status = :status1 OR status = :status2;

Which most likely results in this:

SELECT * FROM members WHERE (member_id = :mID AND status = :status1) OR status = :status2;

But that's not what you want, so you will have to explicitly use parens like this:

SELECT * FROM members WHERE member_id = :mID AND (status = :status1 OR status = :status2);

Alternatively, you can use IN so that there's no OR:

SELECT * FROM members WHERE member_id = :mID AND status IN (:status1, :status2);
Sign up to request clarification or add additional context in comments.

1 Comment

answered in record time and very well explained - thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.