使用PHP PDO和MySql时绑定IS NULL或NULL

时间:2013-09-11 08:14:24

标签: php mysql pdo

如何在以下方案中绑定NULL。无论我做什么,我都无法让它发挥作用。

if ($type == 1) {
    $self   = 'NULL';
    $parent = 'NULL';
}

$findThis = $conn->prepare('select count(id) as exists from table where id = :id and self = :self and parent = :parent';

$findThis->execute(array(
    ":id"     => $id,
    ":self"   => $self,
    ":parent" => $parent
));

2 个答案:

答案 0 :(得分:3)

更新。通过我已经了解到所有可以在一个查询中完成

$sql = 'select 1 from table where id = ? and self <=> ? and parent <=> ?';
$stm = $conn->prepare($sql);
$stm->execute([$id,$self,$parent]);
$exists = $stm->fetchColumn();

您还必须修改您的查询。

$sql = 'select count(id) as exists from table where id = ? and ';

if ($type == 1) {
    $sql .= 'self IS NULL and parent IS NULL'
    $data = [$id];
} else {
    $sql .= 'self = ? and parent = ?';
    $data = [$id,$self,$parent];
}
$stm = $conn->prepare($sql);
$stm->execute($data);

答案 1 :(得分:1)

对于空值,您必须在sql中使用IS NULL