0

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

1
  • You are double-encoding the data; once inside the while-loop and then again before closing the database connection. You should only encode it once, when echoing it. Commented Dec 21, 2013 at 9:06

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

I got this output: [{"title":"\u0628\u0631\u0628\u0631\u064a \u0665\u0660\u066a","description":"\u062a\u062e\u0641\u064a\u0636\u0627\u062a \u0628\u0631\u0628\u0631\u064a \u0665\u0660\u066a \u0644\u0645\u062f\u0629 \u0634\u0647\u0631 ","country":"saudi","city":"riyadh","rate":"50%"}]. Any idea why this would fail to be converted to JSONObject in java?
0

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);
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.