Bind IS NULL or NULL when using PHP PDO and MySql

社会主义新天地 提交于 2020-01-14 04:28:12

问题


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

回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/18735955/bind-is-null-or-null-when-using-php-pdo-and-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!