0

I'm working on a search script with pagination but can't get it to work properly.

Here is my query:

$query = "SELECT COUNT(*) FROM server_data WHERE trash = '0' AND server_address LIKE '%$search%' OR title LIKE '%$search%' OR short_desc LIKE '%$search%'";

This is to count how many results there are in the database.

Here is my query for the actual data:

$query = "SELECT * FROM server_data WHERE trash = '0' AND server_address LIKE '%$search%' OR title LIKE '%$search%' OR short_desc LIKE '%$search%' ORDER BY id DESC $limit";

For some reason, this is returning results where trash = 1 and trash = 0, when it should only be returning where trash = 0 obviously. Anybody have any idea why this could be happening?

1
  • 4
    WHERE trash = '0' AND (server_address LIKE '%$search%' OR title LIKE '%$search%' OR short_desc LIKE '%$search%') ORDER BY id DESC $limit"; Commented Aug 17, 2014 at 19:35

1 Answer 1

1

Use parenthesis

$query = "SELECT * FROM server_data WHERE trash = '0' AND (server_address LIKE '%$search%' OR title LIKE '%$search%' OR short_desc LIKE '%$search%') ORDER BY id DESC $limit";

Without parenthesis your query is evaluated as follows:

$query = "SELECT * FROM server_data WHERE (trash = '0' AND server_address LIKE '%$search%') OR title LIKE '%$search%' OR short_desc LIKE '%$search%' ORDER BY id DESC $limit";

The reason for this is that AND is "strong" than OR (it's like in math where multiplication is stronger than addition: 3*5+3=15+3=18).

Btw. please make sure $search is properly escaped, otherwise you allow SQL injection.

Sign up to request clarification or add additional context in comments.

2 Comments

Would using a prepared statement be good enough as far as preventing SQL injection?
Yes, that would fix this. Maybe also $limit has to be handled (at least casted to int).

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.