1

I have webservice written in PHP that reads from the local database and output the result in JSON.

However, I am unable to output it into a JSONArray.

Here is the php script

<?php
$username = "root";
$password = "";
$hostname = "localhost"; 

$response=array();

//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) 
or die("Unable to connect to MySQL");

//select a database to work with
$selected = mysql_select_db("test",$dbhandle) 
or die("Could not select test");

//execute the SQL query and return records
$result = mysql_query("SELECT name, country FROM android");

$response["infos"] = array();   

while ($row = mysql_fetch_assoc($result)) {

    $info = array();
$info["name"]=$row["name"];
$info["country"]=$row["country"];

    print(json_encode($info));

}

//close the connection
mysql_close($dbhandle);
?>

This is the output from the webservice

{"name":"develop","country":"mru"}{"name":"fufu","country":"tutu"}  {"name":"chikaka","country":"aceVentura"}

But I have been told that this is not in JSONArray.

What am I missing here?

Thank you

1
  • 1
    You're echo'ing multiple json strings rather than just one. I'll add an asnwer to elaborate. Commented Jan 25, 2013 at 15:50

1 Answer 1

7

In your example you're echo'ing out multiple JSON strings because your output code is within a while loop. There should only be one output for the JSON string. The code below will give you a two dimensional array in JSON format.

$info = array();

while ($row = mysql_fetch_assoc($result)) 
{
     $arr = array();
     $arr["name"] = $row["name"];
     $arr["country"] = $row["country"];
     $info[] = $arr;
}

echo json_encode($info);
Sign up to request clarification or add additional context in comments.

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.