问题
I've been using PDO::quote to generate SQL statements. I use the generated SQL to create a memcached
key. I'd like to avoid having to create a connection solely for the purpose of escaping SQL values.
What is the purpose of needing to establish a connection to use PDO::quote method and can it be avoided?
回答1:
Because PDO is an abstraction layer, and each database's quoting methods differ. PDO must know WHICH database you're going to be using to be able to use the proper quoting/escaping API calls.
回答2:
If you know the driver that the SQL is going to be used with, just write a function of your own, e.g.
/**
* @param {string|int|null} $data
* @return string
*/
function quote ($data) {
if (is_float($data) || is_int($data)) {
return $data;
} else if (is_string($data)) {
return '\'' . addslashes($data) . '\'';
} else if ($data) {
throw new Exception('Invalid data type.');
} else {
return 'NULL';
}
}
An example use case: You have a CLI program that is used to generate SQL code that will be executed later by another program. In this scenario, establishing MySQL connection is redundant and might be unwanted.
回答3:
You need a connection because the notion of escaping variables only makes sense when in the context of a database connection with respect to which they are to be escaped. Different characters might be interpreted differently, say, by MySQL and PostgreSQL, or depending on the character set of the connection. So it does not make sense to talk about escaping variables in a vacuum, you need some notion of how the resulting string will be interpreted.
Maybe you could use something else as a key to memcached.
来源:https://stackoverflow.com/questions/7919503/is-there-a-way-of-using-php-pdoquote-method-without-creating-a-connection