0
 $word ="50%";
 $searchSQL = "SELECT * FROM discounts WHERE keyword LIKE '%$word%' ";

when I execute this query it returns no results. I assume the issue is the % sign which is a wild card in mysql. what would be the correct way to search for that $word

cppit
  • 4,478
  • 11
  • 43
  • 68

3 Answers3

3

try something like this,

 $word ="50%";
 $searchSQL = "SELECT * FROM discounts WHERE keyword LIKE '%$word%' escape '%'";

As a sidenote, the query is vulnerable with SQL Injection if the value(s) came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.

Community
  • 1
  • 1
John Woo
  • 258,903
  • 69
  • 498
  • 492
  • yeah I have $keyword mysql escape string and strip_tags to avoid that. – cppit Jan 06 '13 at 05:58
  • 1
    [SQL injection that gets around mysql_real_escape_string()](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) – John Woo Jan 06 '13 at 05:59
  • +1 ...and [answer](http://stackoverflow.com/a/12118602/1723893) in comment link is better than votest in **How to prevent SQL injection in PHP?** – NullPoiиteя Jan 06 '13 at 06:24
2

You try to search the %? If not, change keyword = '%$word%' to keyword LIKE '%$word%'. If you do, escape the % with: LIKE '50\%' ESCAPE '\'":

$word ="50\\%";
$searchSQL = "SELECT * FROM discounts WHERE keyword LIKE '%$word%' ESCAPE '\' ";
Yam Mesicka
  • 6,243
  • 7
  • 45
  • 64
  • this is perfect didnt know you could escape using sql.I was going to use the php addslashes(); – cppit Jan 06 '13 at 05:54
1

You have to add a leading slash before special chars when doing a query in MySQL. So like this:

$word = "50\\%";
Vahid Farahmand
  • 2,528
  • 2
  • 14
  • 20