如何使用Like%Operator避免SQL查询中的SQL注入。 只有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?

You can escape the string using mysql_real_escape_string and add the % wildcards afterwards.

When you run the query use mysql_real_escape_string() as follows:

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();

...