【问题标题】:Send json array to add multiple records in mysql to php script using volley in android在android中使用volley发送json数组以将mysql中的多条记录添加到php脚本
【发布时间】:2018-10-13 09:43:33
【问题描述】:

我正在尝试在数据库中添加多条记录,我正在使用 android 中的 volley 中的字符串请求方法将 json 数组发送到 php 脚本以添加这些记录。但是在 php 中没有得到 json 数组的结果。我只想在 mysql 中添加多条记录,为什么要将 json 数组发送到脚本以通过获取其中的所有数据来添加这些记录

这里是插入数据功能

private void InsertData() {

if(arrayList.size()>0) {
Toast.makeText(getApplicationContext(), "list not null "+i+arrayList.size(), 
 Toast.LENGTH_LONG).show();

//for (i=0;i<arrayList.size();i++) {
    //Toast.makeText(getApplicationContext(),"inside for loop", Toast.LENGTH_LONG).show();


    StringRequest stringRequest = new StringRequest(Request.Method.POST,
            Constants.insert_macthes,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {
                        JSONObject jsonObject = new JSONObject(response);


                        if (jsonObject.getInt("success") == 1) {

                            Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();

                        } else

                            Toast.makeText(getApplicationContext(), "not added", Toast.LENGTH_LONG).show();

                        dis = jsonObject.getString("message");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }


            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                        Toast.makeText(MyMatchas.this,
                                "Error time out",
                                Toast.LENGTH_LONG).show();
                    } else if (error instanceof AuthFailureError) {
                        //TODO
                        Toast.makeText(MyMatchas.this,
                                "Auth Error time out",
                                Toast.LENGTH_LONG).show();
                    } else if (error instanceof ServerError) {
                        //TODO
                        Toast.makeText(MyMatchas.this,
                                "Server Error time out",
                                Toast.LENGTH_LONG).show();
                    } else if (error instanceof NetworkError) {
                        //TODO
                        Toast.makeText(MyMatchas.this,
                                " Network Error time out",
                                Toast.LENGTH_LONG).show();
                    } else if (error instanceof ParseError) {
                        Toast.makeText(MyMatchas.this,
                                "Parse Error time out",
                                Toast.LENGTH_LONG).show();
                        //TODO
                    }

                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            JSONArray array=new JSONArray();

            JSONObject jsonObject=new JSONObject();
            for(i=0;i<arrayList.size();i++)
            {
                Log.v("fetching record:",arrayList.get(i).getId());
                arr[i]="dog_id"+arrayList.get(i).getId()+"dog_name"+arrayList.get(i).getDog_name()+"score"+arrayList.get(i).getDog_score()+"user_id"+ String.valueOf(SharedPrefManager.getInstance(MyMatchas.this).getUserid());
                try {
                    //Log.v("put in json:",arrayList.get(i).getId());
                    jsonObject.put("dog_id",arrayList.get(i).getId());
                    jsonObject.put("dog_name",arrayList.get(i).getDog_name());
                    jsonObject.put("score",arrayList.get(i).getDog_score());
                    jsonObject.put("user_id",String.valueOf(SharedPrefManager.getInstance(MyMatchas.this).getUserid()));

                } catch (JSONException e) {
                    Log.v("error exceptiion:",arrayList.get(i).getId());
                    e.printStackTrace();
                }
                array.put(jsonObject);
            }
            HashMap<String ,String> params=new HashMap<String, String>();
            Log.v("All data:",jsonObject.toString());
            Log.v("json object data:",array.toString());
            params.put("params",array.toString());

            return params;
        }
    };


    // Creating RequestQueue.
    RequestQueue requestQueue = Volley.newRequestQueue(MyMatchas.this);

    // Adding the StringRequest object into requestQueue.
    requestQueue.add(stringRequest);

    // }
  // Toast.makeText(getApplicationContext(),dis,Toast.LENGTH_LONG).show();

 }

这是 PHP 脚本

   <?php
 $con=mysqli_connect("localhost","m","rt","Friend");

 if($_SERVER['REQUEST_METHOD']=='POST'){

$arr = $_POST['params'];





 $json = json_decode($arr,true);
    echo $json;
foreach($json as $obj){

$Sql_Query = "INSERT INTO Match_list (dog_id,score,dog_name,User_ID) values 
   ('$obj->dog_id','$obj->dog_name','$obj->score','$obj->user_id')";

   if($con->query($Sql_Query) === TRUE)
   {

    die(json_encode(array("success"=>1,"message"=>"Data Added 
 Successfuly")));



   }


      }


   }

  mysqli_close($con);
 ?>

【问题讨论】:

  • 这是因为查询失败并且永远不会解析为true。 “INSERT INTO Match_list (dog_id,score,dog_name,User_ID) values ('$obj->dog_id','$obj->dog_name','$obj->score','$obj->user_id')”仍然是没有替换的字符串。尝试将您的变量包装在 {} ...VALUES ('{$obj-&gt;dog_id}', '{$obj-&gt;dog_name}'... 中或将它们连接起来而不是 ...VALUES'. $obj-&gt;dog_id . "', '". $obj-&gt;dog_name ."...
  • 确保通过打印出来并在您的 sql 客户端中手动尝试来测试您的查询
  • 仍然是同样的问题,没有获取数据请帮助我,并且只有 arraylist 中的最后一个列表数据位于我在 android 中使用日志消息看到的 json 数组中
  • echo $Sql_Query$Sql_Query = "INSERT INTO... 之后的结果是什么?
  • 我已经尝试过手动添加数据,但我认为它没有从 android volley 字符串请求方法获取 json 数组,而且我已经在 json 数组中检查了 [] 方括号不在 json 数组中来自安卓

标签: java php android mysql android-volley


【解决方案1】:

您需要为每次保存新值创建新对象

 JSONArray array = new JSONArray();
 JSONObject jsonObject;
 GettingVaccineData gettingVaccineData;
 for (int i = 0; i < vaccineData.size(); i++) {
   jsonObject = new JSONObject();
   gettingVaccineData = vaccineData.get(i);
   try {

     jsonObject.put("LCID", reqResponse);
     jsonObject.put("LVID", gettingVaccineData.getID());
     jsonObject.put("LVNAME", gettingVaccineData.getNAME());
     jsonObject.put("LSCHEDULE", scheduleDays.get(i));
     jsonObject.put("LGIVEN", "NULL");
     jsonObject.put("LSTATUS", "not given");
     jsonObject.put("LHOSPITAL", "NULL");


   } catch (JSONException e) {
     e.printStackTrace();
   }
   array.put(jsonObject);

【讨论】:

    【解决方案2】:

    您可以像这样访问值:

    echo $json[0]["dog_id"];
    

    【讨论】:

      猜你喜欢
      • 2015-07-21
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      • 2018-10-10
      相关资源
      最近更新 更多