0

I have an ArrayList() in my android app containing names of books. I am using android Volley library for server requests. I want to add all these books in my BookList(table) in my database which is in the server. I want to do it using a single server request i.e. using a single php file. How can this php code be written such that it inserts all these values in the table using loop? Some Codes will be really helpful

3
  • 1
    convert the arraylist into json string, and send it to the server. PHP will then json_decode the json, loop, and just run the insert query for each row. Commented Mar 5, 2019 at 3:49
  • 1
    Check here ,this might help you ! Commented Mar 5, 2019 at 3:50
  • @Afif Zafri Can you please post some example code about how to get this done? Commented Mar 6, 2019 at 18:53

1 Answer 1

0

Found the answer with the help from the comments. Firstly, I created JSONArrays from the arrayLists. Then I posted them to php via android volley.

private Map params;

    JSONArray bookNamesJSON = new JSONArray(Arrays.asList(bookNames));
    JSONArray bookAuthorsJSON = new JSONArray(Arrays.asList(bookAuthors));
    JSONArray subjectsJSON = new JSONArray(Arrays.asList(subjects));


    params = new HashMap<>();
    params.put("candidateId", id + "");
    params.put("bookName",bookNamesJSON.toString());
    params.put("authorName",bookAuthorsJSON.toString());
    params.put("subjectName",subjectsJSON.toString());
    params.put("reqDate",date);

Then in php I had to do this:

$candidateId=$_POST["candidateId"];
$reqDate=$_POST["reqDate"];
$subjectName = json_decode($_POST["subjectName"])[0];
$bookName = json_decode($_POST["bookName"])[0];
$authorName = json_decode($_POST["authorName"])[0];


$response = array();
foreach ($subjectName as $i => $subject) 
{
    $stmt = $conn->prepare("INSERT INTO BookRequisition VALUES (?,?,?,?,?);");
    $stmt->bind_param("dssss", $candidateId, $subject, $bookName[$i], $authorName[$i], $reqDate);
    $stmt->execute();
}


$response["success"] = true;



echo json_encode($response);

Hope this helps someone.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.