实转义字符串和 PDO

在从 mysql库迁移之后,我正在使用 PDO。我用什么来代替旧的 real_escape_string函数?

我需要转义单引号,这样它们就会进入我的数据库,我认为可能有一个更好的方法来处理这个问题,而不需要在我所有的字符串中添加(ing)斜杠。我该用什么?

139423 次浏览

You should use 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.

Use prepared statements. Those keep the data and syntax apart, which removes the need for escaping MySQL data. See e.g. this tutorial.

PDO offers an alternative designed to replace mysql_escape_string() with the PDO::quote() method.

Here is an excerpt from the PHP website:

<?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'