Andrea Bellitto
Andrea Bellitto

Reputation: 383

Pass string array to PHP script as POST

I am trying to pass a string array to a PHP script as POST data in an Android app but i have an issue.

this is my client side code:

ArrayList<NameValuePair> querySend = new ArrayList<NameValuePair>();
for (Stop s : stops) {
                querySend.add(new BasicNameValuePair("stop_data[]", s.getNumber()));
            }
HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://www.myURL/myPHPScript.php");
                httppost.setEntity(new UrlEncodedFormEntity(querySend));
                HttpResponse response = httpclient.execute(httppost);

and this is my PHP script code:

foreach($_GET['stop_data'] as $stop) {
  // do something
}

If i run my java code i will get this response error from php script:

Warning: Invalid argument supplied for foreach() in /web/htdocs/www.myURL/myPHPScript.php on line 6
null

otherwise if i will put the request on my browser manully in this way:

http://www.myURL/myPHPScript.php?stop_data[]=768&stop_data[]=1283

i will give the correct answer!

if i try the same code, but if i POST not an array but a single string passing and receiving stop_data variables without [] it works! I can't understand where is the mistake!! It is possible that the [] in BasicNameValuePair String name are doing some codification mistaken? I need to pass an array, how i have to do?

Upvotes: 0

Views: 1068

Answers (1)

Patato
Patato

Reputation: 1472

you use POST method and in php code you should use $_POST

try this

foreach($_POST['stop_data'] as $stop) {
  // do something
}

this way is using GET method

http://www.myURL/myPHPScript.php?stop_data[]=768&stop_data[]=1283

Upvotes: 1

Related Questions