简体   繁体   English

Perl DBI:转义LIKE准备的语句

[英]Perl DBI: Escaping a LIKE prepared statement

I have a query that is binding a parameter to a LIKE statement as follows: 我有一个将参数绑定到LIKE语句的查询,如下所示:

my $sth = $dbh->prepare('SELECT foo FROM bar WHERE baz LIKE ?');
$sth->execute("%$like%");

However, $like is a value that is entered by the user. 但是, $like是用户输入的值。 So if the value contains any special characters recognised by the LIKE clause ( & , _ , \\ ), these are passed unescaped to the database and parsed as wildcard or escape characters. 因此,如果值包含LIKE子句( &_\\ )识别的任何特殊字符,这些特殊字符将不转义地传递到数据库,并解析为通配符或转义符。 For example if the user inputs %value , the query that will be submitted is: SELECT foo FROM bar WHERE baz LIKE '%%value' , rather than LIKE '%\\%value , which is what I would expect. 例如,如果用户输入%value ,将提交的查询为: SELECT foo FROM bar WHERE baz LIKE '%%value' ,而不是LIKE '%\\%value ,这是我期望的。

Currently I am using regular expressions to escape the field manually: 目前,我正在使用正则表达式手动对字段进行转义:

# Escape LIKE wildcard characters
$like =~ s!\\!\\\\!g;
$like =~ s!%!\\%!g;
$like =~ s!_!\\_!g;

my $sth = $dbh->prepare('SELECT foo FROM bar WHERE baz LIKE ?');
$sth->execute("%$like%");

but it feels like the escaping is something DBI should be able to handle. 但感觉逃脱是DBI应该能够处理的事情。 I played around with DBI::quote , but this is designed for quoting entire fields, so in this case it would also quote the % symbols I am adding, and the documentation for DBI::quote specifically states: 我使用了DBI::quote ,但是它是为引用整个字段而设计的,因此在这种情况下,它还会引用我要添加的%符号,并且DBI::quote的文档专门指出:

The quote() method should not be used with "Placeholders and Bind Values". quote()方法不应与“占位符和绑定值”一起使用。

Is there a better way to bind a user-supplied input to a LIKE clause while escaping the input and adding relevant wildcard characters, without resorting to manually escaping the input? 有没有更好的方法可以将用户提供的输入绑定到LIKE子句,同时转义输入并添加相关的通配符,而无需手动转义输入?

Despite what the documentation for DBI::quote says, LIKE parameters are a bit of a special case. 尽管DBI::quote的文档中有说明,但LIKE参数有点特殊。 What you want to do is almost what you already have in your example: first make sure there are no user-provided metacharacters by applying quote to the user-provided string (you do this with regexps in your example), then add your own metacharacters (the percent signs, in this case), then use it as food for the bind parameter. 您想要做的几乎是示例中已经具备的功能:首先通过在用户提供的字符串上加上quote来确保没有用户提供的元字符(在示例中使用regexp进行此操作),然后添加自己的元字符(在这种情况下为百分号),然后将其用作bind参数的食物。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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