查询和DB_Select之间的zend转换

时间:2011-10-31 01:50:43

标签: php mysql regex zend-framework

所以我正在使用这个程序http://code.google.com/p/ecartcommerce/source/browse/library/Ecart/Db/Table/Select/Disassemble.php?edit=1生成一个字符串,该字符串对应于用于创建该查询的zend db select命令。

但是当我在WHERE

中使用IN()语句时,事情就搞砸了

所以假设我有

"SELECT * FROM j WHERE id IN (1,2,3,5,6)";

我使用该类转换它,

当我检查输出时,它删除了IN子句中数字之间的括号,因此它变为

->where("id IN 1,2,3,4,5,6"),虽然它应该是->where("id IN (1,2,3,4,5,6)")

任何人都知道如何解决这个问题?

我怀疑它与_addWhere方法有关:

protected function _addWhere($where)
    {
        $result = '';

        $where = 'AND ' . $where;

        $replacement = true;
        while ($replacement) {

            $replacement = false;
            $parts = preg_split(
                '/(\(.+\)+)/U', $where, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
            );

            foreach ($parts as $part) {
                if (!preg_match('/\(.+?\)/', $part)) {
                    continue;
                }
                if (strstr($part, ' AND ') || strstr($part, ' OR ')) {
                    continue;
                }
                $replacement = preg_replace('/^\s*\((.+)\)\s*$/', '$1', $part);
                $where = str_replace($part, $replacement, $where);
            }
        }

        $parts = preg_split(
            '/(\(.*\))/U', $where, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
        );
        foreach ($parts as $part) {
            if (preg_match('/^\(.*\)$/', $part)) {
                $replacement = str_replace(
                    array('AND', 'OR'), array('AND--', 'OR--'), $part
                );
                $where = str_replace($part, $replacement, $where);
            }
        }
        $parts = preg_split(
            '/(AND|OR)\s/', $where, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
        );

        $type = 'where';
        for ($i = 0 ; $i < count($parts) ; $i++) {
            if ('OR' == $parts[$i]) {
                $type = 'orWhere';
            } else {
                $type = 'where';
            }
//            $subQuery = str_replace('--', '', trim($parts[++$i],'() '));
            $subQuery = preg_replace('/^\s*\((.+)\)\s*$/', '$1', $parts[++$i]);
            $subQuery = str_replace('--', '', $subQuery);
            $result .= "\r\t" . "->{$type}(\""
                    . $this->_replaceLongTableName(trim($subQuery)) . '")';
        }
        return $result;
    }

它特意搞砸了$replacement = preg_replace('/^\s*\((.+)\)\s*$/', '$1', $part);行...

1 个答案:

答案 0 :(得分:-1)

要在where子句中使用IN参数,请尝试以下方式

$i = array(1,2,3,4,5,6);

$select = $this->select()->from('table','*')->where('i = (?)',$i);

当where的参数为数组时,Zend会自动按“,”

拆分