我需要我的Android应用程序来更新DB数据。我是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文件中用错误的方法处理数据(或者两者都有?)。
感谢所有试图提供帮助的人!;)
当前SQL查询行中有$person_id,变量名为$id_person,因此SQL字符串不完整。
顺便说一句,mysql_*是php中较旧的mysql扩展,不推荐使用,所以如果你是php的新手,那么可能值得看看新的选项,也就是mysqli或pdo_mysql(http://php.net/manual/en/mysqlinfo.api.choosing.php)
顺便说一句,您真的不想像那样直接将参数传递到DB查询中,因为它为SQL注入攻击打开了大门。例如,对于mysqli扩展,您通常会使用绑定的params-http://php.net/manual/en/mysqli-stmt.bind-param.php