【发布时间】:2016-09-11 05:15:56
【问题描述】:
我需要我的 Android 应用来更新数据库数据。我对 Android 开发和 PHP 都是新手,所以这对我来说有点新,但我真的需要这样做。这是我得到的:
相关的一段代码(发送到服务器的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();
}
我写的'msg'字符串(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 文件中以错误的方式使用它们(或者可能两者兼而有之?)。
感谢所有试图提供帮助的人! ;)
【问题讨论】: