Reputation: 2550
I am trying to figure out how to print a json array. I am trying to handle this from Android code but it is not working. I believe the problem lies in how I am outputting json. the below doesn't show anything. The script is below:
<?php
// Create connection
$conn=mysqli_connect("localhost","dhdkahd","dsdajdsa","dsadjsajd");
$json = array();
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (!$conn->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $conn->error);
}
$sql='SELECT title, description, country, city, rate FROM discounts';
$rs=$conn->query($sql);
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
/*$rs->data_seek(0);
while($row = $rs->fetch_assoc()){
echo $row['title'] . '<br>';
}*/
while ( $row = $rs->fetch_assoc() )
{
$json[] = json_encode($row,JSON_UNESCAPED_UNICODE);
}
}
//echo json_decode($json);
echo json_encode($json);
mysqli_close($conn);
?>
thanks in advance
Upvotes: 0
Views: 76
Reputation: 913
You call json_encode twice. To fix it, change your code to:
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
/*$rs->data_seek(0);
while($row = $rs->fetch_assoc()){
echo $row['title'] . '<br>';
}*/
while ( $row = $rs->fetch_assoc() )
{
$json[] = $row;
}
}
//echo json_decode($json);
echo json_encode($json);
mysqli_close($conn);
?>
Upvotes: 0
Reputation: 239270
You can only call json_encode
once. You're double-encoding everything.
The line where you're adding data to the array needs to be
$json[] = $row;
Then, when the array is built up, you encode the entire thing in one single call:
echo json_encode($json);
Upvotes: 2