gpt4 book ai didi

php - Android 到 JSON 到 PHP 到 MySQL

转载 作者:行者123 更新时间:2023-11-30 01:21:30 25 4
gpt4 key购买 nike

我正在尝试将一些 STRING 变量作为 JSON 从 android 发送到 PHP。我使用互联网上的指南之一完成了此任务,但不幸的是它不起作用,并且我无法使用 StackOverflow 上的其他类似问题来解决它。

这是我的 Android 代码:-

JSONObject jsonObject= new JSONObject();
JSONArray jsonArray=new JSONArray();

public class sendData extends AsyncTask<String, String, Void> {

@Override
protected Void doInBackground(String... params) {

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://bdp.site40.net/sendRegData.php");

try {
HttpEntity httpEntity = new StringEntity(jsonArray.toString());
httpPost.setEntity(httpEntity);
httpClient.execute(httpPost);
}
catch (IOException e) {
}

return null;
}
}

public void onClickSubmitButton(View view) throws JSONException {

jsonObject.put("name",name);
jsonObject.put("blood",blood);
jsonObject.put("cell",cell);
jsonObject.put("email", email);
jsonObject.put("address",address);
jsonObject.put("country",country);
jsonObject.put("state",state);
jsonObject.put("city",city);

jsonArray.put(jsonObject);

new sendData().execute();

}

这是我的 PHP 代码:-

<?php 

$json = file_get_contents("php://input");
$data = json_decode($json);
$name = $data[0]->name;
$blood = $data[0]->blood;
$cell = $data[0]->cell;
$email = $data[0]->email;
$address = $data[0]->address;
$country = $data[0]->country;
$state = $data[0]->state;
$city = $data[0]->city;
$con = mysql_connect("","","") or die(mysqli_connect_error());
$db = mysql_select_db("",$con) or die(mysqli_connect_error());
mysql_query("INSERT INTO Donors(Name,Blood,Mobile,E-Mail,Address,Country,State,City)VALUES('$name','$blood','$cell','$email','$address','$country','$state','$city')");

?>

经过一番尝试后,我将范围缩小到了这样一个事实:问题在于我将数据发送到 PHP 脚本和/或 PHP 脚本接收数据的方式。任何人都可以找出问题并纠正它吗?谢谢!

注意事项:

  1. 出于隐私考虑,我已经删除了 MySQL 用户名、密码、数据库名称和主机(显然)。
  2. 所有 8 个变量均为字符串格式。

最佳答案

删除行:

httpPost.setHeader("JSONObject", jsonObject.toString());
httpPost.getParams().setParameter("JSONArray", jsonArray);

并将 JSON 内容放入 POST 正文中:

HttpEntity entity = new StringEntity(jsonArray.toString());
httpPost.setEntity(entity);

您还需要修改 PHP 脚本才能正确处理 JSON 数组。

...
$name = $data[0]->name;
$blood = $data[0]->blood;
$cell = $data[0]->cell;
...

关于php - Android 到 JSON 到 PHP 到 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18480320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com