我有这个代码/查询:
if ($a == $b) {
$type = 1;
} else {
$type = null;
}
$this->query(
'DELETE FROM users WHERE userid = ? AND type = ?',
array($userid, $type)
);
如果$type
为null
,Buy mysql不理解第二种情况,不会删除该行。
我知道在查询中定义 null 的正确方法是使用 IS NULL
,但在我的例子中,它不适合。
我能以某种方式通过变量传递 null 吗?
最佳答案
当然可以让 WHERE
子句本身知道值和 IS NULL
之间的切换,但需要额外的条件和额外的占位符。在您的情况下,由于查询很简单,我会动态构建它并将参数附加到 array()
以便相应地执行。
// The basic query, with conditions common to either case:
$sql = 'DELETE FROM users WHERE userid = ? AND ';
// For bound parameters...
// $userid will always be present
$params = array($userid);
if ($a == $b) {
// Add an additional parameter for type
$params[] = 1;
// And add to the WHERE clause the type condition
$sql .= ' type = ?';
}
else
// Or the NULL type condition
$sql .= 'type IS NULL';
}
// Execute with the $params array, which has 1 or 2 elements.
$this->query($sql, $params);
为了将其填充到一个查询中,WHERE
子句必须使用 OR
检测 type
变量是否为非空> 条件。一种方法(不是唯一的方法,也许不是最好的方法)看起来像这样:
DELETE
FROM users
WHERE
userid = ?
AND ((? = 1 AND type = ?) OR type IS NULL)
在这种情况下,$type
的值将被传入两次,首先使条件 1=1
为真,然后与 进行实际比较>类型
列。但是正如您所看到的,当使用占位符时,这会变得有些困惑。首先动态构建字符串会更容易。
关于php - 通过 mysql 上的变量发送 "null"不会删除该行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27506497/