5

I have read through many other questions regarding PHP and JSONArray looping. I am sending in a JSONArray of values of different students with their class and studentId from my Android device. Using these values, I search the database for their names and return a JSONArray.

JSON Input: [{"studentId":"2","class":"2a","dbname":"testDb"}]
<?php

 $jsonString = $_POST['json'];  //see comment below

 $jArray = json_decode($jsonString, true);

 $conn = mysql_connect('localhost', 'user', 'pwd' );

mysql_select_db('dbname', $conn);

foreach( $jArray as $obj ){
    $className = $obj['class'];   //String
    $id= $obj['studentId'];       //int

    $result = mysql_query("SELECT name FROM student WHERE class='$className' AND id='$id'");

    $e=mysql_fetch_assoc($result);    //will only fetch 1 row of result
    $output[]=$e;


}

      echo (json_encode($output));

?>

Android

HttpClient client = new DefaultHttpClient();
HttpResponse response;
try{
 HttpPost post = new HttpPost("http://abc/getName.php");
 List<NameValuePair> nVP = new ArrayList<NameValuePair>(2);  
 nVP.add(new BasicNameValuePair("json", studentJson.toString()));  //studentJson is the JSON input

//student.Json.toString() produces the correct JSON [{"studentId":"2","class":"2a","dbname":"testDb"}]

 post.setEntity(new UrlEncodedFormEntity(nVP));
 response = client.execute(post);
if(response!=null){
//process data send from php
}  
}

SOLVED: See answer below

7
  • Update your post with your JSONArray input and the output of print_r($jArray); Commented Sep 21, 2011 at 17:29
  • I just ran this, but first simplified it. Set $jsonString = '[{"regNo":"2","class":"2a","dbname":"TestData"}]' then after $id= $obj['studentId']; I did echo "SELECT name FROM student WHERE class='$className' AND id='$id'" and it worked. (also, I took out any reference to output or mysql). Try outputting your JSON object (after decoding) to ensure it's an array, and the incoming JSON string is not malformed. Commented Sep 21, 2011 at 17:47
  • As @JasonMcCreary said earlier, add the data that you get. Add to the post your var_dump($jsonString); and var_dump($jArray); output. Maybe $jArray is null or so... Commented Sep 21, 2011 at 17:48
  • Thanks guys, that was the problem, $jArray is null... the PHP could not retrieve my JSONArray input Commented Sep 21, 2011 at 18:17
  • I have edited my question to include the part where I send in the JSONArray input Commented Sep 21, 2011 at 18:26

2 Answers 2

7

SOLVED: Finally understood what was the problem. After posting from Android to PHP script, my JSONArray becomes [{\"studentId\":"2\",\"class\":\"2a\",\"dbname\":\"testDb\"}] To remove the "\", use PHP command stripslashes Spent 4 hours debugging!

Hope this will be a good guide for those that wants to send and retrieve data between Android and PHP

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

Comments

1

Here's your problem:

print_r(json_decode('[{"regNo":"2","class":"2a","dbname":"TestData"}]',true));

returns Array ( [0] => Array ( [regNo] => 2 [class] => 2a [dbname] => TestData ) ) meaning your decoded json is put within an array

Use array_shift(json_decode($jsonString, true)); to remove the parent array.

1 Comment

While this is a good point, it doesn't explain the error Invalid argument for foreach() as it should still loop the parent array.

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.