【问题标题】:PDO bind array index (postgresql JSONB) for readingPDO 绑定数组索引(postgresql JSONB)用于读取
【发布时间】:2016-11-10 13:29:16
【问题描述】:

我在 postgresql JSONB 列中存储了一个对象数组,我试图加载第 n 个对象的属性,但未能将其与 PDO 绑定。

测试设置

<?php
error_reporting(E_ALL);
ini_set('display_errors',1);

$Db = new PDO('...');


    $Db->exec('CREATE TABLE public.test (id SERIAL PRIMARY KEY, jb JSONB NOT NULL )');

    $insert = $Db->prepare('INSERT INTO public.test(jb) VALUES (?)');

    $insert->execute([json_encode([
                                     'q' => 'Qst1'
                                     , 'a' => [['txt' => 'Ans1', 'isCorrect' => true], ['txt' => 'Ans2', 'isCorrect' => false], ['txt' => 'Ans3', 'isCorrect' => false], ['txt' => 'Ans4', 'isCorrect' => false]]
                                 ], JSON_NUMERIC_CHECK)]);

如果我读取整个数组,我可以检查

$allAnswers = $Db->prepare("select jb->'a' from public.test where id=?");
$allAnswers->execute([1]);
$result  = json_decode($allAnswers->fetchColumn(),true);
foreach ([0,1,2,3,17] as $answerId) {
    if (!array_key_exists($answerId,$result) ) {
        echo $answerId,':','NULL',"\n";
    }
    else {
        $r = $result[$answerId]['isCorrect'];
        echo $answerId,':',($r?'TRUE':'FALSE'),"\n";
    }
}

但是如果我只需要 nths 我不知道如何绑定它(我没有得到错误只有空值)

$answerIsCorrect = $Db->prepare("select jb->'a'->?->>'isCorrect' from public.test where id = ?");
foreach ([0,1,2,3,17] as $answerId) {
    $succ = $answerIsCorrect->execute([$answerId, 1]);
    if (true !== $succ) {
        die('Execute failed');
    }
    $result = $answerIsCorrect->fetchColumn();
    echo $answerId,':',is_null($result)?'NULL':('true'===$result?'TRUE':'FALSE'),"\n";
}

电流输出

0:NULL 1:NULL 2:NULL 3:NULL 17:NULL

异常输出

0:TRUE 1:FALSE 2:FALSE 3:FALSE 17:NULL

【问题讨论】:

    标签: php json postgresql pdo


    【解决方案1】:

    终于找到了

    $answerIsCorrect = $Db->prepare("select jsonb_extract_path(jb->'a',?)->>'isCorrect' from public.test where id = ?");
    

    而不是

    $answerIsCorrect = $Db->prepare("select jb->'a'->?->>'isCorrect' from public.test where id = ?");
    

    工作

    【讨论】:

      猜你喜欢
      • 2017-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      • 2015-08-15
      • 1970-01-01
      相关资源
      最近更新 更多