【发布时间】:2015-07-13 21:05:34
【问题描述】:
我在字符串中使用数字作为变量来构造逻辑。
这是我拥有的字符串示例
(1 AND 2)
2 AND 1
(1 AND 2) OR (3 AND 4)
1 AND (2 OR 3)
然后我有一个看起来像这样的数组
$this->clause = array(
'1' => (object) array('fieldId' => 'id',
'value' => 1),
'2' => (object) array('fieldId' => 'cost',
'value' => 132),
'3' => (object) array('fieldId' => 'name',
'value' => "Jay's LLC"),
'4' => (object) array('fieldId' => 'first',
'value' => "Mike"),
);
我正在尝试将字符串(1、2、3 和 4)中的值替换为数组中的相应值。
这就是我的字符串完成后的样子
第一个示例“由于逻辑字符串不包含第 3 和 4 条,因此将在字符串末尾使用 'AND' 逻辑添加两者”
(1 AND 2) becomes
( id = '1' AND cost = '132' ) AND name = 'Jay\'s LLC' AND first = 'Mike'
第二个示例“由于逻辑字符串不包含第 3 和 4 条,因此将在字符串末尾使用 'AND' 逻辑添加两者”
2 AND 1 becomes
cost = '132' AND id = '1' AND name = 'Jay\'s LLC' AND first = 'Mike'
第三个例子“由于逻辑字符串不包含第 4 条,那么它将在字符串末尾使用'AND'逻辑添加”
(1 AND 2) OR (3 AND 4) becomes
( id = '1' AND cost = '132' ) OR (name = 'Jay\'s LLC')
最后一个例子
1 AND (2 OR 3) AND 4 becomes
id = '1' (cost = '132' OR name = 'Jay\'s LLC') AND first = 'Mike'
这是我尝试过的
private function getAllWhereClauseStatements()
{
$query = '';
$totalClause = count($this->clause);
if( $totalClause > 0 ){
$query .= 'WHERE ';
if( !empty($this->clauseLogic) ){
$logic = '';
$tmpLogic = $this->clauseLogic;
foreach($this->clause as $key => $cl){
$tmpLogic .= preg_replace('/\b'.$key.'\b/u', $this->getWhereClause($cl), $tmpLogic);
$this->clause->isUsed = 1;
}
if(! empty($logic) ){
$query .= ' ( ' . $logic . ' ) ';
}
foreach($this->clause as $key => $cl){
if( !isset($this->clause->isUsed) || !$this->clause->isUsed){
$query .= ' AND ' . $this->getWhereClause($cl);
$this->clause->isUsed = 1;
}
}
}
}
return $query;
}
private function getWhereClause($cl)
{
return $cl->fieldId . ' = ' . $cl->value;
}
我有 2 个问题需要帮助
- 我在
$this->clause->isUsed = 1;行收到“警告:尝试分配非对象的属性” -
我正在尝试处理最后一个示例“即 1 AND (2 OR 3)”我得到以下结果
1 AND (2 OR 3) 1 AND (2 OR name = 'Jay\'s LLC' ) 1 AND (2 OR 3) 1 AND (2 OR name = 'Jay\'s LLC' ) 1 AND (cost <> '132' OR 3) 1 AND (cost <> '132' OR name = 'Jay\'s LLC' ) 1 AND (cost <> '132' OR 3) 1 AND (cost <> '132' OR name = 'Jay\'s LLC' ) id = '1' AND (2 OR 3) id = '1' AND (2 OR name = 'Jay\'s LLC' ) id = '1' AND (2 OR 3) id = '1' AND (2 OR name = 'Jay\'s LLC' ) id = '1' AND (cost <> '132' OR 3) id = '1' AND (cost <> '132' OR name = 'Jay\'s LLC' ) id = '1' AND (cost <> '132' OR 3) id = '1' AND (cost <> '132' OR name = 'Jay\'s LLC' )
问题似乎是我如何尝试更换工作
如何纠正我遇到的 2 个问题?
已编辑
我通过换行解决了第一个问题
$this->clause->isUsed = 1;
到
$this->clause[$key]->isUsed = 1;
【问题讨论】:
-
你想用这个构建 SQL 查询吗?
-
是的,我正在尝试构建 were 子句
-
您有什么理由不使用PDO and prepared statement?这似乎是一个更简单的解决方案。
-
我正在构建一个类,它将生成一个复杂的 SQL 查询(多个连接、多个 where 子句)每个子句都有不同的条件(= > 或 LIKE)它比准备工作要复杂得多声明。
-
@EdHeal,它不应该因为我将查询构建限制为只编写带有索引的查询。此外,动态查询将在从属服务器上执行,以减少主服务器的负载。