【问题标题】:Tutorial to send data as JsonArray to MySQL in Android using PHP使用 PHP 在 Android 中将数据作为 JsonArray 发送到 MySQL 的教程
【发布时间】:2016-12-12 18:20:27
【问题描述】:

我在 g*ogle 中尝试了几天,以找到任何好的教程。

但是直到现在,我还没有找到。

我在 android 中有一个 json :

[
  {
    "id": "1",
    "nilai": "1"
  },
  {
    "id": "2",
    "nilai": "1"
  },
  {
    "id": "3",
    "nilai": "1"
  },
  {
    "id": "4",
    "nilai": "1"
  },
  {
    "id": "5",
    "nilai": "1"
  }
]

字符串循环idnilai五次,然后我想在按下按钮时将此json发送到服务器。

我要存储的数据库如下所示:

|---|-----|
| ID|Nilai|
|---|-----|
| 1 |  1  |
| 2 |  1  |
|...| ... |

有什么建议或想法吗? 我不介意你用你的应用程序上的代码来回答,至少代码可以帮助我

由于自己对android和php编程的理解有限,无法尝试代码怎么做,但是当我有类似案例的参考或示例时,我可以尝试代码

【问题讨论】:

  • 有人可以帮帮我吗?

标签: php android mysql json


【解决方案1】:

在服务器中使用带有 php 文件的 volley 库。

这是一个有用的链接:

android developers volley

Volley json post tuturial

【讨论】:

  • 感谢先生的建议,但我上次读过那个导师,我不知道它如何与我的项目一起工作,因为导师只是插入一行,而我的,我需要使用按钮一次插入 5 个数据
【解决方案2】:

您想发送类似 [{"id":"1","nilai":"1"},{"id":"2","nilai":"1"},{"id ":"3","nilai":"1"},{"id":"4","nilai":"1"},{"id":"5","nilai":"1"} ]

你可以做的是:

Java/Android

String jsonObjectString="{\"id\":1,\"nilai\":1}";

您可以使用循环来制作任意数量的内容:

ArrayList<String> yourList=new Arrayist<>();
for(int i=0;i<5;i++)
{
  yourList.add("{\"id\":"+(i+1)+",\"nilai\":1}");
}

然后使用 Volley 通过 POST 发送 ArrayList:

String url = "url that handle the request";
    final Context currentContext = CompleteDataActivity.this;
    final StringRequest request = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // success handling code here
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            // error handling code here
        }
    }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> param = new HashMap<>();
            //Post parameter
            for(int i=0;i<yourList.size();i++)
            {
                param.put("jsonObject"+i, yourList.get(i));
            }

            return param;
        }
    };
    H.showLoadingDialog(currentContext);
    MyVolley.getRequestQueue().add(request);

使用此代码获取 .php 的 JSONObject 列表

    for($i=0;$i<5;$i++)
        {
            $var = "jsonObject".$i;
            $jsonObject=json_decode($_POST[$var]);
            $id = $jsonEtape->{'id'};
            $nilai = $jsonEtape->{'nilai'};
            $sql = "your query;";
            mysqli_query($con,$sql);
        }

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 1970-01-01
    • 2015-03-16
    • 2013-12-21
    • 1970-01-01
    • 2015-04-11
    相关资源
    最近更新 更多