1

上面的问题^^^^^没有正确答案

由于该问题中接受的答案导致 MYSQL 页面将查询分开,因此我仍然需要 PHP 中的解决方案,并且此问题中提供的答案中的链接实际上是我需要的。

我正在尝试用whereSQL 中的子句创建一个有用的数组

好吧,让我们假设这些:

where a=b and b=c or d=g and (a=f or x=6)

where a=b and b='d and f' or d=g and (a=f or x=6)

where a=b and b="d and f (or just text)" or d=g and (a=f or x=6)

where "a"=b andb="Note that colum names might be quoted differently in different databases" or d=g and (a=f or x=6)

where "a"='b' andb="as well as values" or d=g and (a=f or x=6)

where "a"='b' andb="multiple levels" or d=g and (a=f or x=6 or (x=5 and v=7))

我想尝试将任何 where 子句(使用 key=value ... 也就是没有子查询)分解成有用的数组?就像是 :

x= array(
array('a' => 'b' , 'b' => 'c'),
array('d' => 'g' , array(array('a' => 'f'),array('x' => '6')),
);

其中 AND 在一个数组中或在新数组中

或任何其他格式,只是为了能够将整个查询重建为我想要的任何内容。

preg_match 足够了吗?

4

2 回答 2

1

根据@Jack 的评论,SQL 解析器在这里是有意义的。例如,使用PHP SQL 解析器

$sql = 'where a=b and b=c or d=g and (a=f or x=6)';

require_once('php-sql-parser.php');
$parser = new PHPSQLParser();
$parsed = $parser->parse($sql);
print_r($parsed);
于 2013-07-09T08:01:50.260 回答
0

我用于我的 codeigniter 框架的以下函数 - 用于更新表

function updateCT($options = array(),$where=array())
{
    // required values
    if(!$this->_required(
        array('id'),
        $where)
    ) return false;

    // set values for updating
    foreach($options as $key=>$val)
    {
        $this->db->set($key,$val);
    }

    // set where clause for updating
    foreach($where as $key=>$val)
    {
        $this->db->where($key,$val);
    }

    $this->db->update(TBL_COMPANY_TYPE);
    return $this->db->affected_rows();
}

对于定义条件和子句,数组格式如下:-

$options=array(
                 'key1'=>array('val1' , 'and'), 
                 'key2'=>array('val2' , 'or'),
             );

现在处理如下数组:-

foreach($options as $key=>$val)
{
    foreach($val as $value=>$condition)
    {
        // now write sql format as your framework
    }
}
于 2013-07-09T07:51:47.563 回答