我正在使用以下代码使用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();
?>
当我在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);
我得到的结果是:
2[{"longtitude":"32.32","latitude":"33.12"}]
导致JSONObject抛出异常,因为它不是有效的JSON数据,它以2开头 有谁知道如何修理它? 这两个代码都来自在线教程,似乎没有这种问题。问题发生在两个不同的MySQL服务器上..
提前致谢
答案 0 :(得分:2)
检查您的PHP代码并确保在print(json_encode($output))
之前的某个地方没有回显“2”。这是唯一可能出错的事。
另外,您应确保在$output=array()
循环之前声明while
。否则,如果没有结果行,则会得到意外的输出。