mckenzie
mckenzie

Reputation: 121

php mysql search

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?

Upvotes: 2

Views: 107

Answers (2)

intuited
intuited

Reputation: 24034

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.

Upvotes: 2

Weltkind
Weltkind

Reputation: 687

SELECT *
FROM newchap
WHERE (company LIKE '%$company%' AND company != '') OR Category LIKE '%$cat%'

Upvotes: 5

Related Questions