php - PDO bind array index (postgresql JSONB) for reading -
i'm storing array of objects in postgresql jsonb column, i'm tring load property of nth's object fails bind pdo.
test setup
<?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 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)]);
if read whole array can check
$allanswers = $db->prepare("select jb->'a' public.test id=?"); $allanswers->execute([1]); $result = json_decode($allanswers->fetchcolumn(),true); foreach ([0,1,2,3,17] $answerid) { if (!array_key_exists($answerid,$result) ) { echo $answerid,':','null',"\n"; } else { $r = $result[$answerid]['iscorrect']; echo $answerid,':',($r?'true':'false'),"\n"; } }
but if need nths don't know how bind (i'm not getting error null values)
$answeriscorrect = $db->prepare("select jb->'a'->?->>'iscorrect' public.test id = ?"); foreach ([0,1,2,3,17] $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"; }
current output
0:null 1:null 2:null 3:null 17:null
excepted output
0:true 1:false 2:false 3:false 17:null
finnaly found it
$answeriscorrect = $db->prepare("select jsonb_extract_path(jb->'a',?)->>'iscorrect' public.test id = ?");
instead of
$answeriscorrect = $db->prepare("select jb->'a'->?->>'iscorrect' public.test id = ?");
worked
Comments
Post a Comment