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
Asked
Modified
6 years, 8 months ago
Viewed
146 times
Part
of PHP and Mobile Development Collectives
3
-
1convert 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.Afif Zafri– Afif Zafri2019-03-05 03:49:21 +00:00Commented Mar 5, 2019 at 3:49
-
1Check here ,this might help you !Swati– Swati2019-03-05 03:50:50 +00:00Commented Mar 5, 2019 at 3:50
-
@Afif Zafri Can you please post some example code about how to get this done?Arnab Banerjee– Arnab Banerjee2019-03-06 18:53:19 +00:00Commented Mar 6, 2019 at 18:53
Add a comment
|
1 Answer
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.