Arnab Banerjee
Arnab Banerjee

Reputation: 165

Loop through values of a JSONArray in php

I have 3 arrayLists in android app. I am sending them to php via android volley POST request like:

public RequestPostBook(long id, ArrayList<String> bookNames, ArrayList<String> bookAuthors, ArrayList<String> subjects,
                           String date,Response.Listener<String> listener)
    {
        super(Method.POST, REGISTER_REQUEST_URL, listener, null);

        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);
    }

    @Override
    public Map<String, String> getParams() {
        return params;
    }

Now I have to use the values in the arrayList in php to execute a series of similar queries. I am trying this in php:

$candidateId=$_POST["candidateId"];
$reqDate=$_POST["reqDate"];
$subjectName=json_decode($_POST["subjectName"]);
$bookName=json_decode($_POST["bookName"]);
$authorName=json_decode($_POST["authorName"]);
$i=0;
foreach($subjectName as $value)
{
    $subject=$subjectName[$i];
    $book=$bookName[$i];
    $author=$authorName[$i];

    $stmt = $conn->prepare("INSERT INTO BookRequisition VALUES (?,?,?,?,?);");

    $stmt->bind_param("dssss", $candidateId, $subject, $book, $author, $reqDate);

    $stmt->execute();

    $i++;
}

When I run this through the app, this is what I am getting in my BookRequisition table:

12100116050(candidateId)    Array(subjectName)    Array(bookName)    Array(authorName)    2019-03-08(reqDate)

Can anyone please help me on how to send the correct values to the table? Thanks in advance.

Upvotes: 0

Views: 46

Answers (1)

Saji
Saji

Reputation: 1394

Please try the below code.

<?php

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

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();
}

?>

Note: You should do the proper validation on the data posted from your device.

Upvotes: 1

Related Questions