My code contain
SELECT * FROM newchap WHERE company LIKE '%$company%' OR Category LIKE '%$ca开发者_StackOverflow社区t%'
It works perfectly however, when the field $company contain empty, it return all result in MYSQL.
How to prevent it?
SELECT *
FROM newchap
WHERE (company LIKE '%$company%' AND company != '') OR Category LIKE '%$cat%'
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.
精彩评论