php 真正的转义字符串和 PDO
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3716373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Real escape string and PDO
提问by John
I'm using PDO after migrating away from the mysql
library. What do I use in place of the old real_escape_string
function?
我在从mysql
图书馆迁移后使用 PDO 。我用什么来代替旧real_escape_string
功能?
I need to escape single quotes so they will go into my database and I think there may be a better way to handle this without add(ing) slashes to all my strings. What should I be using?
我需要转义单引号,以便它们进入我的数据库,我认为可能有更好的方法来处理此问题,而无需向所有字符串添加(ing)斜杠。我应该使用什么?
采纳答案by SteD
You should use PDO Prepare
你应该使用PDO Prepare
From the link:
从链接:
Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.
为将使用不同参数值多次发出的语句调用 PDO::prepare() 和 PDOStatement::execute() 可通过允许驱动程序协商查询计划的客户端和/或服务器端缓存来优化应用程序的性能并元信息,并通过消除手动引用参数的需要来帮助防止 SQL 注入攻击。
回答by PowerAktar
PDO offers an alternative designed to replace mysql_escape_string()with the PDO::quote()method.
PDO 提供了一种替代方案,旨在用PDO::quote()方法替换mysql_escape_string()。
Here is an excerpt from the PHP website:
以下是 PHP 网站的摘录:
<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');
/* Simple string */
$string = 'Nice';
print "Unquoted string: $string\n";
print "Quoted string: " . $conn->quote($string) . "\n";
?>
The above code will output:
上面的代码会输出:
Unquoted string: Nice
Quoted string: 'Nice'
回答by Piskvor left the building
Use prepared statements. Those keep the data and syntax apart, which removes the need for escaping MySQL data. See e.g. this tutorial.
使用准备好的语句。这些将数据和语法分开,从而消除了对 MySQL 数据进行转义的需要。参见例如本教程。