代码之家  ›  专栏  ›  技术社区  ›  TheLovelySausage

PHP PDO PostgreSQL无法确定数据类型

  •  0
  • TheLovelySausage  · 技术社区  · 4 年前

    在将PHP PDO与PostgreSQL一起用于特定查询时,我遇到了一个奇怪的错误,我不明白为什么。

    我有以下代码

    $conn = new PDO($db, $us, $pw);
    
    try {
       $count = $conn->prepare("select count(idno) as count from t_dummy where ( ? is null or idno = ? )");
       $count->execute([null, null]);
       $count_fetch = $count->fetch();
    } catch(Exception $error) {
       echo $error;
    }
    
    var_dump($count_fetch[0]);
    

    如果PDO连接到MySQL数据库,那么它可以正常工作,但当连接到PostgreSQL数据库时,它会失败,并出现以下错误

    could not determine data type of parameter $1
    

    看起来它不喜欢为 ? is null 但我不知道为什么,因为这是在PgAdmin中运行良好的有效PostgreSQL语法

    0 回复  |  直到 4 年前
        1
  •  1
  •   Frank Heikens    4 年前

    使用CAST():

    $conn = new PDO($db, $us, $pw);
    
    try {
       $count = $conn->prepare("SELECT COUNT(idno) AS count FROM t_dummy WHERE ( CAST(? AS integer) IS NULL OR idno = ? );");
       $count->execute([null, null]);
       $count_fetch = $count->fetch();
    } catch(Exception $error) {
       echo $error;
    }
    
    var_dump($count_fetch[0]);