我正在尝试以OOP方式将table_name和conditional_clauses作为参数传递时构造并执行删除查询。我通过将其包装在自定义包装器中来使用PDO。我正在使用带有命名占位符的准备好的语句。在每种情况下,我都在PDO->execute()
函数内部传递了一个关联数组,其中array_keys是所用占位符的名称,而array_value是要替换的对应值。当我想通过WHERE子句指定IS NULL
条件时,仅遇到一种情况。
基本上,如果我想搜索类似的东西:
SELECT * FROM EMPLOYEES WHERE salary > 10000 AND skill IS NULL
我能够动态地构造如下所示的准备好的语句:
$sql = SELECT * FROM employees WHERE salary > :salary AND skill IS :skill
然后以以下方式执行准备好的SQL:
时,我才出现致命错误。并且,我想在包装器中包括检查IS NULL功能。$stmt->execute(["salary" => 10000, "skill" => null])
这是我面临的问题。仅当值为null
请注意-
我想在不使用bindValue()
的情况下达到目的,或者bindParam()函数。我已关闭仿真(因为MySQL可以将所有占位符排序正确)。
使用?
这是参考代码段:
<?php
class DeleteQuery {
protected function where(array $whereCondition, array &$values): string{
$whereClause = ' WHERE ';
$i = 0;
$j = 0;
$hasComparators = array_key_exists("comparators", $whereCondition);
$hasConjunctions = array_key_exists("conjunctions", $whereCondition);
$comparatorCount = $hasComparators ? count($whereCondition["comparators"]) : 0;
$conjunctionCount = $hasConjunctions ? count($whereCondition["conjunctions"]) : 0;
foreach ($whereCondition["predicates"] as $predicate_key => &$predicate_value) {
$whereClause .= $predicate_key;
$whereClause .= ($hasComparators and ($i < $comparatorCount)) ?
' ' . $whereCondition["comparators"][$i++] . ' ' : ' = ';
if (is_array($predicate_value)) {
$whereClause .= "('" . implode("', '", $predicate_value) . "')";
unset($whereCondition['predicates'][$predicate_key]);
} else {
$whereClause .= ':' . $predicate_key;
}
$whereClause .= !($hasConjunctions and ($j < $conjunctionCount)) ?
'' : ' ' . $whereCondition["conjunctions"][$j++] . ' ';
}
$values = array_merge($values, $whereCondition['predicates']);
return $whereClause;
}
public function delete($tblName, $conditions) {
$sql = "DELETE FROM " . $tblName;
$values = [];
if (!empty($conditions) && is_array($conditions)) {
/* If the stmt has WHERE clause */
if (array_key_exists("where", $conditions)) {
$sql .= $this->where($conditions['where'], $values);
}
/* If the stmt has ORDER BY clause */
if (array_key_exists("order_by", $conditions)) {
$sql .= $this->order_by($conditions['order_by']);
}
/* If the stmt has LIMIT clause */
if (array_key_exists("limit", $conditions)) {
$sql .= $this->limit($conditions['limit'], $values);
}
}
echo $sql . PHP_EOL;
print_r($values);
}
}
$deleteConditions = [
"where" => array(
"predicates" => ["skill" => null],
"comparators" => ["IS"],
),
/* other conditional clauses */
];
$obj = new DeleteQuery();
$obj->delete("employees", $deleteConditions);
我正在尝试以OOP方式将table_name和conditional_clauses作为参数传递时构造并执行删除查询。我通过将其包装在自定义包装器中来使用PDO。我是...
IS
运算符不能与表达式一起使用。 IS NULL
和IS NOT NULL
是关键字。