我需要安卓應用來更新數據庫數據。我對Android開發人員和PHP都很陌生,所以這對我來說是新鮮的,但我真的需要這樣做。以下是我的了:使用JSON和PHP更新數據庫(Android)
相關的代碼(JSON對象發送到服務器):
HttpURLConnection conn = null;
OutputStream os = null;
InputStream is = null;
try {
URL url = new URL("my-server/update.php");
JSONObject jsonObject = new JSONObject();
jsonObject.put("id_person", ""+me.getId());
jsonObject.put("name", me.getName());
jsonObject.put("surname", me.getSurname());
jsonObject.put("lat", ""+me.getLatitude());
jsonObject.put("lng", ""+me.getLongitude());
jsonObject.put("phone", ""+123456789);
String msg = jsonObject.toString();
System.out.println(msg);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(20000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(msg.getBytes().length);
conn.connect();
os = new BufferedOutputStream(conn.getOutputStream());
os.write(msg.getBytes());
os.flush();
is = conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
os.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
}
的 '味精' 字符串(JSON)是我寫的
"{"id_person":"1","name":"T","surname":"Test","lat":"12.34","lng":"43.21","phone":"123456"}
而php我使用:
<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);
$id_person = $obj->{'id_person'};
$name = $obj->{'name'};
$surname = $obj->{'surname'};
$lat = $obj->{'lat'};
$lng = $obj->{'lng'};
$phone = $obj->{'phone'};
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("UPDATE person SET name = '$name', surname = '$surname', lat = '$lat', lng = '$lng', phone = '$phone' WHERE id_person = $id_person");
?>
這是幹什麼的: 沒有例外,沒有錯誤。應用的行爲就像完成了一樣,但數據庫沒有發生變化。所以我的猜測是我要麼以錯誤的方式發送數據,要麼在PHP文件中以錯誤的方式處理它們(或者可能兩者都是?)。
感謝大家試圖幫助! ;)
謝謝,我想那將永遠不會工作。但是,即使在我修復此問題之後,我仍然遇到同樣的問題。所以我想還有其他的東西.. 並感謝提示,我會查找它,但現在我真的需要這個工作,直到明天以任何方式... –
如果我設置JSON爲例,並在本地運行它看起來像查詢將在此時有效 - 我建議添加一些回聲語句(如果你的應用程序會顯示原始響應形式的Web服務器,如果它的錯誤)或使用PHP的error_log函數(http://php.net/ manual/en/function.error-log.php)來了解正在發生的事情。 –
因此,該行沒有更新,因爲我通過迴應結果找到了該行。我設法修復了這個「bug」,而所有這一切都是人臉表格中的「p」不是大寫(我不知道它應該是)。將其更改爲Person並且它可以工作。感謝您的第一個提示,我接受你的回答,正如我在評論中提到的解決方案。謝謝。 –