suicidebilly
suicidebilly

Reputation: 295

Can't use AND Operator on a mysqli_query?

I need to filter my query with more than one argument but I can't do this using mysqli_query, instead of mysql_query.

My code works perfectly if I don't use the AND Operator, for example:

$results = mysqli_query($connecDB,"SELECT * FROM table WHERE company='Company1' ORDER BY id DESC");

But if I use the AND Operator:

 $results = mysqli_query($connecDB,"SELECT * FROM table WHERE company='Company1' AND company='Company2' ORDER BY id DESC");

The code doesn't work anymore. I search around and it looks like i need Prepared Statements but I can't find a way to make my code work.

Someone know what i'm doing wrong ?

Upvotes: 0

Views: 222

Answers (4)

user3798282
user3798282

Reputation: 35

Actually, its problem with your logic. You must be using OR instead of AND because because company field could contain only one company out of the two and company field can't contain both the companies simultaneously. So, you must change your $query to the following:

SELECT * FROM table WHERE (company='Company1' OR company='Company2') ORDER BY id DESC

or

SELECT * FROM table WHERE company IN ( 'Company1', 'Company2' ) ORDER BY id DESC

Upvotes: 0

spencer7593
spencer7593

Reputation: 108410

Firstly, there are absolutely no rows for which both predicates will evaluate to true.

MySQL is looking at each individual row, and checking whether the row satisfies the predicates, in this case, whether the result of the entire WHERE clause returns TRUE.

If there's a row that has a value of 'Company1' in the company column, then the first predicate:

company = 'Company1'

will evaluate to TRUE; and the second predicate:

company = 'Company2'

is will evaluate to FALSE.

According to logic of the boolean AND operator, TRUE AND FALSE evaluates to FALSE, so the row will not be returned.

This should be sufficient to explain why the query is returning 0 rows.

If you want the query to return a row when value of the company column matches either 'Company1' or 'Company2', the two predicates can be combined with a boolean OR operator.

Upvotes: 1

SeanWM
SeanWM

Reputation: 16989

Use OR instead of AND:

SELECT * FROM table WHERE (company='Company1' OR company='Company2') ORDER BY id DESC

Upvotes: 0

Danijel
Danijel

Reputation: 12699

Just try with:

SELECT * FROM table WHERE company IN ( 'Company1', 'Company2' ) ORDER BY id DESC

You can't have company that is simultaneously Company1 and Company2.

Upvotes: 5

Related Questions