ilbiffi Posted March 26, 2016 Share Posted March 26, 2016 I'm trying to retrieve data and I want it formatted as json, I'm trying with two scripts, they're not working fully for different reasons, the first formats the data as an array, with square brackets instead of curly ones.$stmt = $link->prepare("select * from x where y = ?");$stmt->bind_param('s', $z);$stmt->execute();$stmt->bind_result($a, $b, $c, $d, $e, $f, $g, $h ,$i);while ($stmt->fetch()) { $output[]=array($a, $b, $c, $d, $e, $f, $g, $h ,$i);}$stmt->close();print json_encode($output);Which gives this output[[7,"xyz","abc","123","lorem ipsum",11,22,33,44],[8,"zyx","cba","321","muspi merol",44,33,22,11]]This other version outputs curly brackets but only displays the first row, not all of them$sql = 'select * from x where y = ?';if ($stmt = $link->prepare($sql)) { $stmt->bind_param('s', $z); $stmt->execute(); $stmt->bind_result($a, $b, $c, $d, $e, $f, $g, $h ,$i); $json = array(); if($stmt->fetch()) { $json = array('a'=>$a, 'b'=>$b, 'c'=>$c, 'd'=>$d, 'e'=>$e, 'f'=>$f, 'g'=>$g, 'h'=>$h, 'i'=>$i); }else{ $json = array('error'=>'no record found'); } $stmt->close();}$link->close();print(json_encode($json));?>I would like to have curly brackets, but something fails in the second script and I can't retrieve all the values, what am I missing? Quote Link to comment Share on other sites More sharing options...
Barand Posted March 26, 2016 Share Posted March 26, 2016 You are missing the [] after $json $json[] = array('a'=>$a, 'b'=>$b, 'c'=>$c, 'd'=>$d, 'e'=>$e, 'f'=>$f, 'g'=>$g, 'h'=>$h, 'i'=>$i); Quote Link to comment Share on other sites More sharing options...
ilbiffi Posted March 27, 2016 Author Share Posted March 27, 2016 You are missing the [] after $json $json[] = array('a'=>$a, 'b'=>$b, 'c'=>$c, 'd'=>$d, 'e'=>$e, 'f'=>$f, 'g'=>$g, 'h'=>$h, 'i'=>$i); There was also a missing "while" in the second script while ($stmt->fetch()) { $json[] = array('a'=>$a, 'b'=>$b, 'c'=>$c, 'd'=>$d, 'e'=>$e, 'f'=>$f, 'g'=>$g, 'h'=>$h, 'i'=>$i); } $stmt->close(); } $link->close(); print json_encode($json); Thanks! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.