Passing JSONArray to PHP with Android

I read many other questions regarding the PHP loop and JSONArray. I am sending JSONArray the values ​​of different students with their class and studentId from my Android device. Using these values, I search the database for my 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

+4
source share
2 answers

SOLVED: I finally realized what the problem was. After publishing from Android to a PHP script, my JSONArray will become [{\"studentId\":"2\",\"class\":\"2a\",\"dbname\":\"testDb\"}] To remove "\", use the PHP stripslashes 4 hours debugging has been completed!

Hope this will be a good guide for those who want to send and retrieve data between Android and PHP.

+6
source

Here is your problem:

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

returns Array ( [0] => Array ( [regNo] => 2 [class] => 2a [dbname] => TestData ) ) , which means that your decoded json is placed in an array

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

+1
source

All Articles