有没有一种方法可以使用PHP PDO :: quote方法而不创建连接? [英] Is there a way of using PHP PDO::quote method without creating a connection?

查看:65
本文介绍了有没有一种方法可以使用PHP PDO :: quote方法而不创建连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 PDO :: quote 来生成SQL语句.我使用生成的SQL创建memcached密钥.我希望避免仅出于转义SQL值的目的而创建连接.

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.

使用PDO :: quote方法需要建立连接的目的是什么?

What is the purpose of needing to establish a connection to use PDO::quote method and can it be avoided?

推荐答案

如果您知道将使用该SQL的驱动程序,则只需编写自己的函数即可,例如

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';
    }
}

一个示例用例:您有一个CLI程序,该程序用于生成SQL代码,稍后将由另一个程序执行.在这种情况下,建立MySQL连接是多余的,并且可能是不必要的.

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.

这篇关于有没有一种方法可以使用PHP PDO :: quote方法而不创建连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆