函数mysql_real_escape_string的PDO等效项是什么? [英] What is the PDO equivalent of function mysql_real_escape_string?
问题描述
我正在将代码从使用mysql_*
修改为PDO
.在我的代码中,我有mysql_real_escape_string()
.在PDO中这相当于什么?
I am modifying my code from using mysql_*
to PDO
. In my code I had mysql_real_escape_string()
. What is the equivalent of this in PDO?
推荐答案
没有,没有!
从技术上讲,有 PDO::quote()
但它很少使用,并且不等同于 mysql_real_escape_string()
Technically there is PDO::quote()
but it is rarely ever used and is not the equivalent of mysql_real_escape_string()
That's right! If you are already using PDO the proper way as documented using prepared statements, then it will protect you from MySQL injection.
下面是使用预准备语句(pdo)的 safe 数据库查询的示例
Below is an example of a safe database query using prepared statements (pdo)
try {
// first connect to database with the PDO object.
$db = new \PDO("mysql:host=localhost;dbname=xxx;charset=utf8", "xxx", "xxx", [
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
} catch(\PDOException $e){
// if connection fails, show PDO error.
echo "Error connecting to mysql: " . $e->getMessage();
}
并且,现在假设已建立连接,您可以像这样执行查询.
And, now assuming the connection is established, you can execute your query like this.
if($_POST && isset($_POST['color'])){
// preparing a statement
$stmt = $db->prepare("SELECT id, name, color FROM Cars WHERE color = ?");
// execute/run the statement.
$stmt->execute(array($_POST['color']));
// fetch the result.
$cars = $stmt->fetchAll(\PDO::FETCH_ASSOC);
var_dump($cars);
}
现在,您可能已经知道,我还没有使用任何东西来转义/消毒$_POST["color"]
的值.借助PDO和预准备语句的强大功能,此代码可安全地防止myql注入.
Now, as you can probably tell, I haven't used anything to escape/sanitize the value of $_POST["color"]
. And this code is secure from myql-injection thanks to PDO and the power of prepared statements.
值得注意的是,出于安全原因,应在上面的DSN
中将charset=utf8
作为属性传递,并始终启用
PDO以异常形式显示错误.
It is worth noting that you should pass a charset=utf8
as attribute, in your DSN
as seen above, for security reasons, and always enable
PDO to show errors in the form of exceptions.
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
因此数据库查询中的错误将不会显示敏感数据,例如您的目录结构,数据库用户名等.
so errors from you database queries won't reveal sensitive data like your directory structure, database username etc.
最后但并非最不重要的一点是,有些时候您不应该信任PDO 100%,并且势必会采取一些额外的措施来防止sql注入,其中一种情况是,如果您使用的是mysql的过时版本[ mysql =< 5.3.6 ]
如在此答案中所述
Last but not least, there are moments when you should not trust PDO 100%, and will be bound to take some extra measures to prevent sql injection, one of those cases is, if you are using an outdated versions of mysql [ mysql =< 5.3.6 ]
as described in this answer
但是,与使用以mysql_
好读
这篇关于函数mysql_real_escape_string的PDO等效项是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!