Norman
Norman

Reputation: 6365

Bind IS NULL or NULL when using PHP PDO and MySql

How can I bind NULL in the following scenario. No matter what I do, I can't get it to work.

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
));

Upvotes: 1

Views: 371

Answers (2)

Your Common Sense
Your Common Sense

Reputation: 157861

UPDATE. By an by I have learned that all can be done in one query

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

You have to amend your query as well.

$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);

Upvotes: 3

xdazz
xdazz

Reputation: 160843

For null values, you have to use IS NULL in the sql instead.

Upvotes: 1

Related Questions