我应该在" LIKE"中逃脱通配符吗? SQL查询?

时间:2012-05-21 07:23:09

标签: php sql-injection security

假设我有一个LIKE sql语句存储在这样的变量中:

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

我可以通过转义通配符%_来阻止sql注入攻击的哪个实例?

2 个答案:

答案 0 :(得分:2)

使用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...

答案 1 :(得分:1)

很简单:

写一个这样的函数:

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

现在您的查询:

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

这应该有效!我在自己的项目中测试过!! 玩得开心;)