为什么要使用ATTR_EMULATE_PREPARES,是mysql_real_escape_string的替代品吗? 在PDO中[重复]

This question already has an answer here:

  1. is there any alternatives in PDO as in mysql is mysql_real_escape_string?
  2. why we should set 'false' -> ATTR_EMULATE_PREPARES constant?
</div>
  1. you don't have to use mysql_real_escape_string in PDO in Prepared statement
  2. not necessarily. You can use either way

To answer edited question

NO, there are no alternatives. You should use prepared statements.

Using the mysql extension, the only way to dynamically embed values into queries is:

$query = "SELECT ... WHERE foo = '$bar'";

To avoid syntax errors which in the worst case can be exploited as SQL injections, you need to apply mysql_real_escape_string to $bar here to escape the value properly. Read The Great Escapism (Or: What You Need To Know To Work With Text Within Text) if you don't know what this means.

Prepared statements offer a completely different way to use dynamic values by entirely separating the query and the values:

$stmt = $db->prepare('SELECT ... WHERE foo = :bar');
$stmt->execute(array(':bar' => $bar));

This is actually sent to the database as two separate pieces; the syntax can never be messed up or exploited because the two pieces are never actually merged to begin with.

This feature is not supported by all databases though, some (older) databases still want the old style, non-prepared escaped queries. ATTR_EMULATE_PREPARES gives the option to, well, emulate prepared statements. You can still use the $db->prepare()->execute() API in your code, but behind the scenes PDO will escape the value and concatenate it into the query. To explicitly forbid PDO to do that and force it to use the native prepared statements API the database offers, set ATTR_EMULATE_PREPARES to false.

You should do this if your database natively supports prepared statements; all halfway recent databases do. If you let PDO emulate prepared statements, there's still a small chance of SQL injections under certain conditions (mostly under artificially constructed multi-byte connection encoding situations AFAIK).

Under no circumstances do you use a function from the mysql extension together with the PDO extension; it wouldn't work to begin with, since mysql_real_escape_string needs a separate database connection established through mysql_connect.