0

I am writing a small service in php to output a JSON string. The service is ultimately consumed by an Android JSONObject, if that helps. To keep it short, I have:

<?php
mysql_connect('localhost','myUser','myPwd') or die('Cannot connect to the DB');
mysql_select_db('ctgscott_myDB') or die('Cannot select the DB');
$query=mysql_query("SELECT name FROM customers ORDER BY name ASC");

while($e=mysql_fetch_assoc($query))
$output[]=$e;
print(json_encode($output));    

mysql_close();

?>

The problem is the output arrives in the form:

[{"name":"Client Number1"},{"name":"Client Number2"}]

'name' is the column header for the name field in the 'customer' table and it is unnecessary for me to repeat it... I am struggling to format the output like:

{"name":["Client Number1","Client Number2"]}

Any help would be greatly appreciated. Thanks!

2 Answers 2

1

You need to have a multi-dimensional array instead. Try using this:

mysql_connect('localhost','myUser','myPwd') or die('Cannot connect to the DB');
mysql_select_db('ctgscott_myDB') or die('Cannot select the DB');
$query=mysql_query("SELECT name FROM customers ORDER BY name ASC");

$names['name'] = array();
while($e = mysql_fetch_assoc($query)) {
   $names['name'][] = $e['name'];
}

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

6 Comments

Thanks, Christopher! It looks like we are half way there. The output is now: {"name":[{"name":"Client Number2"},{"name":"Test Client"}]}
Sorry, let me clean that up: {"name":[{"name":"Client Number1"},{"name":"Client Number2"}]} Any other thoughts on pulling the 'name' out of the []? The problem I have is that on the consumption side without extra parsing the Android JSONObject will take either a key/value or a key/array() pair. Of course more work could be put in there... just trying to keep it simple on one side or the other. :)
Changing 'mysql_fetch_assoc($query)' to 'mysql_fetch_row($query) gave me: ... {"name":[["Client Number1"],["Client Number2"]]} ... so close. Maybe i'll just go ahead with the parsing on the receiving side.
Sorry - thats my bad. I have amended the code above that should correct it.
Brilliant! It works perfectly. Output={"name":["Client Number1","Client Number2"]} ...Thanks Christopher! Damn, I am new to StackOverflow and they won't let me 'up arrow' this question... boo.
|
0

here is good article to fetch data from mysql to android using php http://blog.sptechnolab.com/2011/02/10/android/android-connecting-to-mysql-using-php/. i hope you like it.

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.