Jump to content

problem with json formatting


ilbiffi

Recommended Posts

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?

Link to comment
Share on other sites

 

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!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.