2

My code contain

SELECT * FROM newchap WHERE company LIKE '%$company%' OR  Category LIKE '%$cat%'

It works perfectly however, when the field $company contain empty, it return all result in MYSQL.

How to prevent it?

2 Answers 2

5
SELECT *
FROM newchap
WHERE (company LIKE '%$company%' AND company != '') OR Category LIKE '%$cat%'
Sign up to request clarification or add additional context in comments.

Comments

2

Since the % wildcard can be any combination of characters, if it's empty you're selecting any company at all; your query in that case is

SELECT * FROM newchap WHERE company LIKE '%%' OR  Category LIKE '%$cat%'

You could add an AND condition into the SQL to filter out the case where the company is empty, or you could just check for that in PHP. If this is a common case that should be faster, since it will save you running a query at all.

Also — and this is very important — if there's any chance that $company or $cat could contain user input, you should be using a parameterized SQL query. otherwise you're creating a vulnerability for an SQL injection.

Comments

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.