鍍金池/ 問答/PHP  數(shù)據(jù)庫/ PHP pdo鏈接postgresql數(shù)據(jù)庫,where條件中使用json報(bào)錯(cuò)

PHP pdo鏈接postgresql數(shù)據(jù)庫,where條件中使用json報(bào)錯(cuò)

  • 最近在使用postgresql數(shù)據(jù)庫的json格式,發(fā)現(xiàn)pdo查詢報(bào)錯(cuò)
  • 源碼如下
<?php

    // 使用PDO鏈接
    $pdo = new PDO("pgsql:host=127.0.0.1;port=5432;dbname=postgres","postgres","");
    $statement = $pdo->prepare("select * from test where account::jsonb ? '111'");
    $statement->execute();
    var_dump($statement->errorInfo());
    $rs = $statement->fetch();
    var_dump($rs);
    
    // 原生鏈接 查詢
    $p = pg_connect("host=127.0.0.1 port=5432 dbname=postgres user=yluchao password=''");
    $rs = pg_query($p, "select * from test where account::jsonb ? '111'");
    var_dump(pg_fetch_all($rs));



/*create table test
(
  id bigserial primary key,
  account jsonb not null default '{}',
  name varchar(255) not null default ''
);*/

圖片描述

如圖 使用pdo查詢報(bào)錯(cuò),使用原生的pgsql鏈接則可以查詢

回答
編輯回答
未命名

在PHP中PDO::prepare里包含?就表示是占位符。直接使用PDO::query就不會(huì)有這個(gè)問題。

其實(shí)關(guān)于這個(gè)問題,官方早就有回復(fù):https://bugs.php.net/bug.php?...

解決方案:關(guān)閉本地模擬預(yù)處理

$pdo = new PDO(...);
$pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES ,false);

或者

$pdo->prepare($sql,[\PDO::ATTR_EMULATE_PREPARES=>false]);

http://php.net/manual/en/pdo....

PHP 默認(rèn)開啟本地模擬,關(guān)閉ATTR_EMULATE_PREPARES后會(huì)將prepare操作發(fā)送到數(shù)據(jù)庫服務(wù)器由數(shù)據(jù)庫服務(wù)器來進(jìn)行操作。

2018年1月2日 04:00
編輯回答
故林
    PDO 占位符寫的有問題,不知道這個(gè)test 表數(shù)據(jù)結(jié)構(gòu)是怎么樣的
    // 使用PDO鏈接
    $pdo = new PDO("pgsql:host=127.0.0.1;port=5432;dbname=postgres","postgres","");
    $statement = $pdo->prepare("select * from test where account = ?");
    $statement->execute(array(111));
    var_dump($statement->errorInfo());
    $rs = $statement->fetch();
    var_dump($rs);
2018年6月5日 02:59