-1

I'm using the following code to access my DB using PHP

<?php
$host = "localhost";
$user = "**MASKED**";
$password = "**MASKED**";
$database = "parkfinder_zxq_coordinates";

$connection = mysql_connect($host, $user, $password) or die("couldn't connect to server");
$db = mysql_select_db($database, $connection) or die("couldn't select database.");
//$request_parked = $_REQUEST['parked'];
$request_long = $_REQUEST['longtitude'];
$request_lat = $_REQUEST['latitude'];
$q = mysql_query("SELECT * FROM Coordinates");
while ($e = mysql_fetch_assoc($q))
    $output[] = $e;

print (json_encode($output));

mysql_close();
?>

when I read the response using this code in Java:

                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("http://parkfinder.zxq.net/default.php");
                    httppost.setEntity(new UrlEncodedFormEntity(coordinatesToSend));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();

                    String result = EntityUtils.toString(entity);
                    Log.d("RESULT", result);
                    JSONObject json_data = new JSONObject(result);

I'm getting that the result is:

2[{"longtitude":"32.32","latitude":"33.12"}]

which causes the JSONObject to throw an exception as this is not a valid JSON data, it starts with 2 Does anyone know how to fix it? both codes are taken from tutorials online, which didn't seem to have this kind of problem. the problem happened on two different MySQL servers..

Thanks in advance

La bla bla
  • 8,558
  • 13
  • 60
  • 109

1 Answers1

2

Check your PHP code and make absolutely sure you are not echoing out a "2" somewhere before your print(json_encode($output)). That is the only thing that could be wrong.

As an aside, you should make sure to declare $output=array() before your while loop. Otherwise if you have no result rows you will get unexpected output.

Francis Avila
  • 31,233
  • 6
  • 58
  • 96
  • Well, it's not the only thing could be wrong, but it's far and away the most likely. OP -- try putting a print statement earlier, print out an asterisk or something, see if it shows up between the 2 and the square bracket. – Michael Lorton May 23 '12 at 22:25
  • I didn't echo anything, however adding the $output=array() removed the 2 from the string.. weird, but works! thanks! – La bla bla May 23 '12 at 23:01
  • also had to remove the [] from the $output[] = $e; as JSON must start with { and it added [ before. works great now! – La bla bla May 23 '12 at 23:11
  • JSON *absolutely* can start with a `[`! JSON can represent an object or an array. See [the JSON spec](http://www.json.org/) and the [JSON validator](http://jsonlint.com/) – Francis Avila May 24 '12 at 00:39