Is there a way of using PHP PDO::quote method with

2019-08-03 12:19发布

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?

标签: php pdo quote
3条回答
小情绪 Triste *
2楼-- · 2019-08-03 12:42

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楼-- · 2019-08-03 12:48

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.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-08-03 12:50

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.

查看更多
登录 后发表回答