Reputation: 21386
I have a mysql table like below;
+----+-------------+-------------+-------------+-------------+
| Sl | Column1 | Column2 | Column3 | Column4 |
+----+-------------+-------------+-------------+-------------+
| 1 | Data1A | Data2A | Data3A | xxxxxx |
+----+-------------+-------------+-------------+-------------+
| 2 | Data1B | Data2B | Data3B | yyyyyy |
+----+-------------+-------------+-------------+-------------+
| 3 | Data1C | Data2C | Data3C | xxxxxx |
+----+-------------+-------------+-------------+-------------+
| 4 | Data1D | Data2D | Data3D | yyyyyy |
+----+-------------+-------------+-------------+-------------+
| 5 | Data1E | Data2E | Data3E | xxxxxx |
+----+-------------+-------------+-------------+-------------+
I just want to make a query with LIKE statement for columns 1,2 and 3, so that it will search for similar data in those columns with keywords. Also I want to filter the results using the data in column4, which means, I want the privilage to filter away results which will be specific to col4, either xxxxxx or yyyyyy.
I made a syntax $query = "SELECT * FROM table WHERE Column1 LIKE'%$keyword%' OR Column2 LIKE'%$keyword%' OR Column3 LIKE'%$keyword%' AND Column4 = 'xxxxxx'";
But this is not working, and my syntax $query = "SELECT * FROM table WHERE Column1 LIKE'%$keyword%' AND Column4 = 'xxxxxx'";
is working well.
But I want to check for similarities in col2 and col3 also. But it will give me result without filtering col4.
Upvotes: 0
Views: 3746
Reputation: 4709
You have to remember how the comparative function. You need to evaluate all the OR conditions as a group and then match it with the last AND condition. You need to use brackets around the OR conditions to make them evaluate as a group.
Upvotes: 2
Reputation: 7896
Your solution lies in grouping the disjunction (ORs) together, like so:
$query = "SELECT * FROM table WHERE (Column1 LIKE '%$keyword%' OR Column2 LIKE'%$keyword%' OR Column3 LIKE'%$keyword%') AND Column4 = 'xxxxxx'";
Upvotes: 1
Reputation: 22044
I think you need to put brackets around your OR
conditions like so...
SELECT * FROM table WHERE
(Column1 LIKE'%$keyword%' OR Column2 LIKE'%$keyword%' OR Column3 LIKE'%$keyword%') AND Column4 = 'xxxxxx';
Upvotes: 5