0

I have a simple SQL Query in my PHP Code. The %search% is a input where the user is able to write something.

My problem is that the online = '0' gets ignored and there are also Data with online = '1'

$sql = "SELECT * from baw.entrys WHERE online = '0' and title like '%search%' or weight like '%search%' ORDER BY id DESC";

If I take the or away and leave my SQL Query like this it works.

$sql = "SELECT * from baw.entrys WHERE online = '0' and title like '%search%' ORDER BY id DESC";
Mika G.
  • 142
  • 2
  • 13

3 Answers3

2

AND has higher precedence than OR so your first WHERE actually looks like

(online = '0' and title like '%search%') or weight like '%search%'

which means it will match any row where weight is like %search%, regardless of the value of online. What you actually want is:

online = '0' and (title like '%search%' or weight like '%search%')

so just change the WHERE clause to be like the above line and it should work fine.

Nick
  • 138,499
  • 22
  • 57
  • 95
0
$sql = "SELECT * from baw.entrys WHERE online = '0' and (title like '%search%' or weight like '%search%') ORDER BY id DESC";

You need to use parenthesis for your OR statement otherwise the OR will also include your online = '0'.

You are facing this error because in your code you look for online column to be 0

and title to be like search OR the weight to be like search so if it find the weight column to be like search it will include it no matter what the other values are cause it become true.

Have a look at this thread about true/false table and you will realize what was wrong pretty fast.

pr1nc3
  • 8,108
  • 3
  • 23
  • 36
0

Try this my friend

$sql = "SELECT * from baw.entrys WHERE online = '0' and (title like '%search%' or weight like '%search%') ORDER BY id DESC"