Is there a way of using PHP PDO::quote method without creating a connection?

百般思念 提交于 2019-12-11 01:59:35

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!