PHP ADOdb / PDO相当于Perl DBI quote_identifier?

时间:2010-08-17 13:57:06

标签: php pdo adodb

在我目前的工作中,标准做法是直接使用mysql_query()和朋友。在构建大型查询时,由于我们的标准部署在MySQL上,因此表名只是插入并被反引号包围(部分,虚假示例):

$sql .= "from `$tablename`";

我正试图摆脱MySQL主义,并且作为其中的一部分,转向PDO和/或ADOdb。但是,我对Perl比PHP更熟悉,我很惊讶我无法轻易找到DBI's quote_identifier的等价物,它可以是唯一的表名,也可以是整套识别信息(目录,模式) ,表)。我忽略了一些明显的东西吗?

2 个答案:

答案 0 :(得分:1)

不幸的是,在PHP领域没有任何东西可以与DBI的强大功能相提并论。 PDO是一个有价值的起点。

您最好的选择不是尝试创建特定于数据库的标识符引用,而是要告诉数据库遵循标准。 Turn on ANSI quotes,意味着您可以使用双引号来标识列和表名。大多数其他数据库(包括Postgres和SQLite)都接受此标准指定格式。某些(like MSSQL)也具有类似的设置,可以从非标准默认值切换到双引号。

作为一个警告,这意味着在引用字符串文字值而不是双精度时,总是必须使用单引号。此外,大多数标识符不必引用,除非它们是SQL关键字或由数据库保留。

使SQL可移植所需的其他步骤还有批次。您可能希望更进一步,实际使用SQL构建器或ORM。

答案 1 :(得分:0)

/**
 * @param string|string[]$identifiers
 * @param string $tableName
 * @param string $dbName
 * @return string[]|string
 */
static public function quoteIdentifiers($identifiers, $tableName='', $dbName='' ){
    if( is_array($identifiers) ){
        $result = array();
        foreach( $identifiers as $identifier ){
            $result[] = self::quoteIdentifiers($identifier, $tableName, $dbName);
        }
    }else{
        $result = '`'.str_replace('`','``',$identifiers).'`'; // escape backtick with backtick
        if( $tableName ){
            $result = '`'.$tableName.'`.'.$result;
        }
        if( $dbName ){
            $result = '`'.$dbName.'`.'.$result;
        }
    }
    return $result;
}

用法:

$columns = quoteIdentifiers(array('my col1', 'my col2'), 'table');
$sql = 'SELECT '.join(',', $columns);
$sql=.' FROM '.quoteIdentifiers('table');
=> SELECT `table`.`my col1`,`table`.`my col2` FROM `table`

奖金(智能报价值,无需连接!):

/**
 * quote a value or values
 * @param string|string[]|int|int[] $value
 * @return string[]|string
 */
static public function quoteValues($value) {
    if( is_array($value) ){
        $result = array_map(__METHOD__, $value);
    }elseif( $value===true ){
        $result = 'TRUE';
    }elseif( $value===false ){
        $result = 'FALSE';
    }elseif( $value===null ){
        $result = 'NULL';
    }elseif( is_int($value) OR is_float($value) OR  ( is_string($value) AND $value===strval($value*1) ) ){
        $result = strval($value); // no quote needed
    }else{
        $result =  "'".str_replace(
                        array('\\',     "\0",   "\n",   "\r", "'",      '"',    "\x1a"),
                        array('\\\\',   '\\0',  '\\n', '\\r', "\\'",    '\\"',  '\\Z'),
                        strval($value)). "'";
    }
    return $result;
}
相关问题