简体   繁体   English

转义字符串

[英]Escaping strings

I'm using PDO and was under the impression that prepare escaped apostrophes but I can see that isn't the case. 我使用的是PDO,给人的印象是准备转义的撇号,但我看到情况并非如此。 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();

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

PDO::quote($data)

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). 如果应用程序仅使用准备好的语句,则开发人员可以确保不会发生SQL注入(但是,如果使用未转义的输入来构建查询的其他部分,则仍然可以进行SQL注入)。

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 作为占位符

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

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