使用 PHP mysqli:其中 bind_param 中的子句可能是 NULL


Using PHP mysqli: where clause in bind_param might be NULL

我有一个绑定查询,其中 where 子句中的列可能为 null 或可能具有值。

示例代码:

select
    name
from
    table
where
    typeId = 1

有时查询可能包含空值,即

select
    name
from
    table
where
    typeId is null

通常,对于绑定查询,我会执行以下操作:

select
    name
from
    table
where
    typeId = ?

但是,如果 typeId 为空,我不会得到结果集。只有我硬编码typeId is null我才会得到结果。您知道对此的解决方案或解决方法吗?

仅供参考,查询的代码为:

    $sql = "select name from table where typeId = ?"; 
    $params = array(null);
    $types = array("i");
    $param_refs = array();
    foreach ($params as $key => $value) {
        $param_refs[$key] = &$params[$key];
    }
    $stmt = $mysqli->prepare($sql);

    call_user_func_array(array($stmt, "bind_param"), array_merge($types, $param_refs));
    $stmt->execute();
    $result = $stmt->get_result();
    $fields = $result->fetch_fields();
    while($row = $result->fetch_assoc()){
          //code to handle each row of result
    }

使用<=>运算符

$sql = "select name from table where typeId <=> ?";