简体   繁体   中英

How to avoid SQL Injection in SQL query with Like % Operator. only php mysql

How to avoid SQL Injection in SQL query with Like Operator for only PHP and Mysql? can this be done using string functions?

or can anybody tell me what should I do to prevent attacks of like % operator?

您可以使用mysql_real_escape_string对该字符串进行转义,然后添加%通配符。

运行查询时,请使用mysql_real_escape_string() ,如下所示:

mysql_query("SELECT field FROM table WHERE field2 LIKE '%".mysql_real_escape_string($yourVar)."%'");

There are few things you could do to make it secure. First of you have to figure out what type of data you will be searching: number, string etc.

I would suggest using PHP's PDO library , preparing the query and binding the value according to the data type you should receive.
Below an example where the received data is supposed to be string. Notice the PARAM_STR .

...

$value = "apple";

$sth = $dbh->prepare('SELECT name FROM fruit WHERE type LIKE :something');
$sth->bindParam(':something', '%'.$something.'%', PDO::PARAM_STR);
$sth->execute();

...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM