Ard Ard - 3 months ago 28
MySQL Question

How To insert Array to MySQL with Volley Android Studio

I have some problem, I searched on google and stackoverflow, but I couldn't find anything that would answer my problem.

My case is that I can't save Array list into my database.

I have Multiple selection, and a put it to RecycleView like this
I get the position and value from the

Recyleview
, then put into an array, and next I put each of them into a HashMap, save it successfull, but all data is saved with duplicate values (same with Array Length)

This is data from my DB, is duplicated saved, but i have select two different item

StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jPesan = new JSONObject(response);
boolean pesan = jPesan.names().get(1).equals("success");
if (pesan == true){
PD.dismiss();
Toast.makeText(getApplicationContext(),
"Data Personil Terlibat Berhasil di Simpan",
Toast.LENGTH_SHORT).show();
}else if(pesan == false){
Toast.makeText(getApplicationContext(),
"Terjadi Kesalahan",
Toast.LENGTH_SHORT).show();
}

} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
PD.dismiss();
Toast.makeText(getApplicationContext(),
"Terjadi Kesalahan Jaringan", Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() {

// HERE I PUT ARRAY TO HASMAP

Map<String, String> params = new HashMap<String, String>();
for (int i = 0; i < arrPers.length; i++){
params.put("nrp", arrPers[i]);
params.put("id-jadwal", idJadwal);
}

return params;


}
};

// Adding request to request queue
MyApplication.getInstance().addToReqQueue(postRequest);

}

Answer

You can send arrays by specifying the key:

Map<String, String> params = new HashMap<String, String>();
for (int i = 0; i < arrPers.length; i++){
    params.put("nrp["+i+"]", arrPers[i]);//specify the key of the array you post
    params.put("id-jadwal", idJadwal);
}

In your PHP you should have somthing like:

var_dump($_POST['nrp']);// array('1110112','1110113'....);

foreach($_POST['nrp'] as $option) { //just as an example
    //insert each element in db ($option and user id)
}
Comments