简体   繁体   English

在Perl中转义单引号

[英]escape single quotes in perl

I have the following code: 我有以下代码:

my $body = $in{'article'};

Here is my database insertion code: 这是我的数据库插入代码:

my $stmt = $db->prepare("insert into news_articles (createdate, userid, status, title, inline, content, attribution, pending) values(unix_timestamp(), $user->{'uid'}, 0, '$title', '$pullquote', '$body', '$attr', 0)");

It seems to fail when i have a single quote inside the $body variable. 当我在$body变量中使用单引号时,它似乎失败了。

I've tried escaping it using: 我尝试使用以下方法转义它:

$body = $db->quote($body);

And also: 并且:

$body = qq($body);

I'm very new to Perl, but how can I safely escape single quotes prior to the insertion? 我是Perl的新手,但是如何在插入之前安全地转义单引号呢?

$body = $db->quote($body) is the correct way to do this, but note that the quote method also adds the outer quotation marks, so you would use just $body in your SQL statement instead of '$body' $body = $db->quote($body)是执行此操作的正确方法,但请注意quote方法还添加了外部引号,因此您将在SQL语句中仅使用$body而不是'$body'

However, using prepare together with placeholders is by far the best method all-round. 但是,将prepare与占位符一起使用是迄今为止最好的方法。 It supplies the necessary quoting for you, and also allows a prepared statement to be reused several times with different execute parameters 它为您提供了必要的报价,还允许将准备好的语句使用不同的execute参数重复使用多次。

I find here documents useful for writing SQL statements with some layout so that they are readable. 我在这里发现一些文档这些文档对于以某种布局编写SQL语句很有用,以使它们易于阅读。 Your code would look like this 您的代码如下所示

my $body = $in{article};

my $stmt = $db->prepare(<<END_SQL);
INSERT INTO news_articles (createdate, userid, status, title, inline, content, attribution, pending)
VALUES (UNIX_TIMESTAMP(), ?, ?, ?, ?, ?, ?, ?)
END_SQL

$stmt->execute($user->{'uid'}, 0, $title, $pullquote, $body, $attr, 0);

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

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