Php 通过mysql上的变量发送“null”不会删除该行
我有以下代码/查询:Php 通过mysql上的变量发送“null”不会删除该行,php,mysql,pdo,Php,Mysql,Pdo,我有以下代码/查询: if ($a == $b) { $type = 1; } else { $type = null; } $this->query( 'DELETE FROM users WHERE userid = ? AND type = ?', array($userid, $type) ); Buy mysql不理解第二种情况,如果$type为null,则不会删除该行 我知道在查询中定义null的正确方法是使用IS null,但在我的情况下,
if ($a == $b) {
$type = 1;
} else {
$type = null;
}
$this->query(
'DELETE FROM users WHERE userid = ? AND type = ?',
array($userid, $type)
);
Buy mysql不理解第二种情况,如果$type为null,则不会删除该行
我知道在查询中定义null的正确方法是使用IS null,但在我的情况下,它不适合
我可以通过某种方式将null传递给变量吗?MySQL不知道columnname=null的位置。MySQL确实理解columnname为null的位置
试试这个:
if ($a == $b) {
$this->query(
'DELETE FROM users WHERE userid = ? AND type = ?',
array($userid, 1)
);
} else {
$this->query(
'DELETE FROM users WHERE userid = ? AND type IS NULL',
array($userid)
);
}
MySQL不理解columnname=null的位置。MySQL确实理解columnname为null的位置
试试这个:
if ($a == $b) {
$this->query(
'DELETE FROM users WHERE userid = ? AND type = ?',
array($userid, 1)
);
} else {
$this->query(
'DELETE FROM users WHERE userid = ? AND type IS NULL',
array($userid)
);
}
当然,可以使WHERE子句本身感知值和IS NULL之间的切换,但需要附加条件和附加占位符。在您的例子中,由于查询很简单,我将动态地构建它,并将参数附加到数组中以便相应地执行
// 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子句必须检测类型变量是否为非null,并带有OR条件。一种方法不是唯一的方法,也可能不是最好的方法看起来是这样的:
DELETE
FROM users
WHERE
userid = ?
AND ((? = 1 AND type = ?) OR type IS NULL)
在本例中,$type的值将传入两次,首先使条件1=1为真,然后实际与type列进行比较。但正如您所看到的,当使用占位符时,这会变得有点混乱。首先,动态构建字符串更容易。当然可以让WHERE子句本身感知值和NULL之间的切换,但需要附加条件和附加占位符。在您的例子中,由于查询很简单,我将动态地构建它,并将参数附加到数组中以便相应地执行
// 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子句必须检测类型变量是否为非null,并带有OR条件。一种方法不是唯一的方法,也可能不是最好的方法看起来是这样的:
DELETE
FROM users
WHERE
userid = ?
AND ((? = 1 AND type = ?) OR type IS NULL)
在本例中,$type的值将传入两次,首先使条件1=1为真,然后实际与type列进行比较。但正如您所看到的,当使用占位符时,这会变得有点混乱。首先,动态构建字符串更容易。您的查询需要更智能,适当时use为NULL,因此我最好在if语句下使用两个查询?一个是NULL,另一个是$type?您的查询需要更智能,并且在适当的时候use是NULL,所以我最好在if语句下使用两个查询?一个是NULL,另一个是$type?OP应该得到更多的解释,而不是尝试这个。很好的一点-你是100%正确的。我在回答中加了一个简短的解释。另外,感谢您回复我的解释请求!这篇文章总是比尝试这篇文章更值得解释。很好的一点——你是100%正确的。我在回答中加了一个简短的解释。另外,感谢您回复我的解释请求!