转义字符串

发布于 2024-10-17 08:42:06 字数 232 浏览 4 评论 0原文

我正在使用 PDO,并且印象中要准备转义撇号,但我发现事实并非如此。我用什么来转义撇号字符串?


$sql = 'SELECT test FROM test WHERE id = :id';
$sth = $dbh->prepare($sql);
$sth->execute(array(':id' => 1));
$red = $sth->fetchAll();

I'm using PDO and was under the impression that prepare escaped apostrophes but I can see that isn't the case. what do I use to escape my strings for apostrophes?


$sql = 'SELECT test FROM test WHERE id = :id';
$sth = $dbh->prepare($sql);
$sth->execute(array(':id' => 1));
$red = $sth->fetchAll();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

泪之魂 2024-10-24 08:42:06

我怀疑虽然您可能使用准备好的语句,但您没有绑定参数。例如,

$val = "Some string with an a'postrophe in it";
$stmt = $pdo->prepare("UPDATE table SET col = '$val'");
$stmt->execute();

您应该使用

$val = "Some string with an a'postrophe in it";
$stmt = $pdo->prepare('UPDATE table SET col = :val');
$stmt->bindParam('val', $val);
$stmt->execute();

或者 至少

$val = "Some string with an a'postrophe in it";
$stmt = $pdo->prepare('UPDATE table SET col = :val');
$stmt->execute(array('val' => $val));

这是使用命名参数,但您也可以使用 ? 作为占位符来使用位置参数

I suspect that whilst you might be using a prepared statement, you are not binding parameters. For example, instead of

$val = "Some string with an a'postrophe in it";
$stmt = $pdo->prepare("UPDATE table SET col = '$val'");
$stmt->execute();

You should use

$val = "Some string with an a'postrophe in it";
$stmt = $pdo->prepare('UPDATE table SET col = :val');
$stmt->bindParam('val', $val);
$stmt->execute();

or at least

$val = "Some string with an a'postrophe in it";
$stmt = $pdo->prepare('UPDATE table SET col = :val');
$stmt->execute(array('val' => $val));

This is using named parameters but you can also use positional ones using ? as a placeholder

溺渁∝ 2024-10-24 08:42:06

我不确定我是否理解你的问题,但这可能有助于 PDO 转义:

PDO::quote($data)

I am not sure I understand your question, but this might help with PDO escaping:

PDO::quote($data)
送你一个梦 2024-10-24 08:42:06

我怀疑您没有正确使用准备好的语句,或者您的代码有问题。

文档 特别指出:

准备语句的参数
不需要被引用;司机
自动处理这个。如果一个
应用程序专门使用准备好的
声明,开发商可以确定
不会发生SQL注入
(但是,如果其他部分
正在建立查询
未转义的输入,SQL注入是
还是有可能的)。

I Suspect you are not using preparred statements correctly, or there is something wrong with your code.

The docs specifically states:

The parameters to prepared statements
don't need to be quoted; the driver
automatically handles this. If an
application exclusively uses prepared
statements, the developer can be sure
that no SQL injection will occur
(however, if other portions of the
query are being built up with
unescaped input, SQL injection is
still possible).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文