user701510
user701510

Reputation: 5763

should I escape wildcards in a "LIKE" sql query?

suppose I have a LIKE sql statement stored in a variable like this:

$movie_title = $_POST['movie_title'];
$query= "SELECT movie FROM movies WHERE title LIKE '%" . $movie_title . "%'";

What instance of an sql injection attack would I prevent by escaping the wildcards % and _?

Upvotes: 1

Views: 2091

Answers (2)

silez
silez

Reputation: 9

Very simple:

Write a function like this:

function sqlwildcardesc($x){
    return str_replace(array("%", "_"), array("\\%", "\\_"), mysql_real_escape_string($x));
}

now your query:

$query= "SELECT movie FROM movies WHERE title LIKE '%".sqlwildcardesc($movie_title)."%'";

this should work! i tested it in my own project!! have fun ;)

Upvotes: 0

Milan Halada
Milan Halada

Reputation: 1934

Using PDO:

$pdo = new PDO(/* db info */);

$original = $_POST['movie_title'];
$wildcarded = '%'.$original.'%';
$stmt = $pdo->prepare('SELECT movie FROM movies WHERE title LIKE :var');
$stmt->bindParam(':var', $wildcarded);
$stmt->execute();
// fetching and stuff...

Upvotes: 2

Related Questions