cppit
cppit

Reputation: 4564

mysql search for % and $ characters no results

 $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

Upvotes: 0

Views: 68

Answers (3)

Yam Mesicka
Yam Mesicka

Reputation: 6601

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 '\' ";

Upvotes: 2

John Woo
John Woo

Reputation: 263823

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.

Upvotes: 3

Vahid Farahmand
Vahid Farahmand

Reputation: 2558

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

$word = "50\\%";

Upvotes: 1

Related Questions