Passing JSONArray to PHP from Android - php

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

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

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.

Related

Converting PHP response string to JSON in Android, always says JSON string is Malformed

I am trying to send data from MSSQL table on server to Android app via PHP. I am using Volley to send the request for data.
The issue is that no matter what I try, Android says the returned JSON encoded string is "Malformed".
I have put the returned JSON string "response" into online JSON decoders and it displays perfectly, yet Andoid says: "Syntax error, malformed JSON{"data":[{"claimNumber":"f265e5e.....}]".
However, if I hardcode a copy and paste of the returned "response" string into a variable "input" in the Android
response function, it works perfectly.
JSONObject jObj = new JSONObject(response); ** Fails - Android says Malformed.
JSONObject jObj = new JSONObject(input); ** Android uses it with no issues.
The following is the method in Android used to receive the PHP response. Have included Log outputs of both the "response" string and
the manually entered "input" string. They are identical, yet Android won't use the actual "response" string.
public void onResponse(String response) {
if (response.equals("failed")) {
Log.d("failed", "failed");
callback.onResponse(null);
return;
}
try {
// Android sees the response returned from the PHP function as always Malformed.
Log.d("response", response);
D/response: - Syntax error, malformed JSON {"data":[{"claimNumber":"f265e5e6513070abd1f711232cfd3a491075f15bc9714cf723e373f02e71a214","xlsLine":"8b3490231cd923c133989dd93574de131b6c388a86153a74eb6ae2507193a008c9d3d0264452cc1bd1113d5a722f3ea7975f322461f486be96e789424459e20bcbaf878f5d0efe09426b90c046d881100e166ef0bfcf8721266383aabf3837a213854e8425e92b722791640576d3c0ce7722ff3de2e6005c85df840bea3b10982b7bcf8bec3398ea03e08e6a2879cb29e0e6c3c05370e1c2cf819e6156991c762b2247e8a5b51edb852bb371aca011eccaa581ed577e74d6bf0f2a71e43e7751e3fa6e5f68c2a6e4ccd4fc338fc2a2ea4a9d98018c52fe5953741a53d7f7a6f1c1e57901d64c957dc1776ab0ed28f5754f7d44008ebc5864cfd34dd3b1f1bf82db49674b8e7a3e381882f7cc1035bfdba114280f6c173e337d1813fb47a9b1aaf1d52faac197f90cced9eea754cf441cb262b3117444ad3a265cefb9593d40cdb8a3ae0235cc06baffbcac493bf45852908b014f063c29d85347e808e7ed4be8688327bf3280759ea1ff187287dcabaaee8859a6da782cd2451e2911fe16ca7d","markerColor":"0","edited":"0"}]}
// If I copy the returned "response" string manually into a variable "input", Android says it's fine.
String input = "{\"data\":[{\"claimNumber\":\"f265e5e6513070abd1f711232cfd3a491075f15bc9714cf723e373f02e71a214\",\"xlsLine\":\"8b3490231cd923c133989dd93574de131b6c388a86153a74eb6ae2507193a008c9d3d0264452cc1bd1113d5a722f3ea7975f322461f486be96e789424459e20bcbaf878f5d0efe09426b90c046d881100e166ef0bfcf8721266383aabf3837a213854e8425e92b722791640576d3c0ce7722ff3de2e6005c85df840bea3b10982b7bcf8bec3398ea03e08e6a2879cb29e0e6c3c05370e1c2cf819e6156991c762b2247e8a5b51edb852bb371aca011eccaa581ed577e74d6bf0f2a71e43e7751e3fa6e5f68c2a6e4ccd4fc338fc2a2ea4a9d98018c52fe5953741a53d7f7a6f1c1e57901d64c957dc1776ab0ed28f5754f7d44008ebc5864cfd34dd3b1f1bf82db49674b8e7a3e381882f7cc1035bfdba114280f6c173e337d1813fb47a9b1aaf1d52faac197f90cced9eea754cf441cb262b3117444ad3a265cefb9593d40cdb8a3ae0235cc06baffbcac493bf45852908b014f063c29d85347e808e7ed4be8688327bf3280759ea1ff187287dcabaaee8859a6da782cd2451e2911fe16ca7d\",\"markerColor\":\"0\",\"edited\":\"0\"}]}";
// Log showing Androids interpretation of the manually entered "input" string
// It matches the "response" string exactly yet "response" string fails.
Log.d("input", input);
D/input: {"data":[{"claimNumber":"f265e5e6513070abd1f711232cfd3a491075f15bc9714cf723e373f02e71a214","xlsLine":"8b3490231cd923c133989dd93574de131b6c388a86153a74eb6ae2507193a008c9d3d0264452cc1bd1113d5a722f3ea7975f322461f486be96e789424459e20bcbaf878f5d0efe09426b90c046d881100e166ef0bfcf8721266383aabf3837a213854e8425e92b722791640576d3c0ce7722ff3de2e6005c85df840bea3b10982b7bcf8bec3398ea03e08e6a2879cb29e0e6c3c05370e1c2cf819e6156991c762b2247e8a5b51edb852bb371aca011eccaa581ed577e74d6bf0f2a71e43e7751e3fa6e5f68c2a6e4ccd4fc338fc2a2ea4a9d98018c52fe5953741a53d7f7a6f1c1e57901d64c957dc1776ab0ed28f5754f7d44008ebc5864cfd34dd3b1f1bf82db49674b8e7a3e381882f7cc1035bfdba114280f6c173e337d1813fb47a9b1aaf1d52faac197f90cced9eea754cf441cb262b3117444ad3a265cefb9593d40cdb8a3ae0235cc06baffbcac493bf45852908b014f063c29d85347e808e7ed4be8688327bf3280759ea1ff187287dcabaaee8859a6da782cd2451e2911fe16ca7d","markerColor":"0","edited":"0"}]}
JSONObject jObj = new JSONObject(input);
jArray = jObj.getJSONArray("data");
} catch (JSONException e) {
e.printStackTrace();
}
}
// GSON print of JSON Object from the manually entered "input" variable.
I/System.out: {
"nameValuePairs": {
"data": {
"values": [
{
"nameValuePairs": {
"claimNumber": "f265e5e6513070abd1f711232cfd3a491075f15bc9714cf723e373f02e71a214",
"xlsLine": "8b3490231cd923c133989dd93574de131b6c388a86153a74eb6ae2507193a008c9d3d0264452cc1bd1113d5a722f3ea7975f322461f486be96e789424459e20bcbaf878f5d0efe09426b90c046d881100e166ef0bfcf8721266383aabf3837a213854e8425e92b722791640576d3c0ce7722ff3de2e6005c85df840bea3b10982b7bcf8bec3398ea03e08e6a2879cb29e0e6c3c05370e1c2cf819e6156991c762b2247e8a5b51edb852bb371aca011eccaa581ed577e74d6bf0f2a71e43e7751e3fa6e5f68c2a6e4ccd4fc338fc2a2ea4a9d98018c52fe5953741a53d7f7a6f1c1e57901d64c957dc1776ab0ed28f5754f7d44008ebc5864cfd34dd3b1f1bf82db49674b8e7a3e381882f7cc1035bfdba114280f6c173e337d1813fb47a9b1aaf1d52faac197f90cced9eea754cf441cb262b3117444ad3a265cefb9593d40cdb8a3ae0235cc06baffbcac493bf45852908b014f063c29d85347e808e7ed4be8688327bf3280759ea1ff187287dcabaaee8859a6da782cd2451e2911fe16ca7d",
"markerColor": "0",
"edited": "0"
}
}
]
}
}
}
Have tried php output with and without slashes. No change... still malformed.
Have tried stripping non-standard chars. There are none.
Have forced charset "UTF-8". No difference.
Have searched and tried every conceivable solution for this on Google. Nothing works.
I'm at a loss as to what to try next. Totally confused on why Android can't use the returned Json string,
but can use it if you manually take the same string and put it in a variable in the code directly.
Can someone tell me if this is a known bug, if the JSON really is malformed or if something else comes to mind?
Thank you
EDIT
Here is the PHP that creates the json to return to Android.
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt2 = sqlsrv_query( $conn3, $tsql1, $params, $options);
$row_count = sqlsrv_num_rows($stmt2);
if ($row_count === false) {
echo("failed");
} else {
while( $userClaims = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC) ) {
$claimNum = $userClaims['ClaimNumber'];
$xls = $userClaims['XLS'];
$color = $userClaims['Color'];
$edited = "0";
$keyvals = (object) array("claimNumber" => $claimNum, "xlsLine" => $xls, "markerColor" => $color, "edited" => $edited);
array_push($response,$keyvals);
}
$encoded = json_encode(array('data' => $response));
EDIT 2
The following is the complete php section of code that creates the json return string. The array is initialized at the top. Have written the php json string to a text file on server and copied the text to a json checker and it works fine.
$response = array();
$i = 0;
$param1 = $token;
$params = array( &$param1);
$tsql1 = "SELECT * FROM Claims WHERE Token = ? AND DeletionFlag = 0";
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt2 = sqlsrv_query( $conn3, $tsql1, $params, $options);
$row_count = sqlsrv_num_rows($stmt2);
if ($row_count === false) {
echo("failed");
} else {
while( $userClaims = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC) ) {
$claimNum = $userClaims['ClaimNumber'];
$xls = $userClaims['XLS'];
$color = $userClaims['Color'];
$edited = "0";
$keyvals = (object) array("claimNumber" => $claimNum, "xlsLine" => $xls, "markerColor" => $color, "edited" => $edited);
array_push($response,$keyvals);
}
$encoded = json_encode(array('data' => $response));
echo $encoded;
}
sqlsrv_close($conn3);
Thank you for your help Andy. I finally figured it out. I found a line of code in the php file that was out of place. It was trying to json_decode an empty string. This is what was generating the extra 36 chars about the malformed string in my actual response. Once I moved it to the correct place, everything started working beautifully. Should have known better, most likely a blasted copy/paste error. Should teach me not to be lazy and actually type ALL my code. Thanks, again!!

Php decoding Jsonarray from jsonobject

Hi i am working on php webservices and i am stucked with receving jsonarray as post request . i am able to receve other objects apart from jsonarray easily. My json structure looks like the following
{
"full_name" :"amn",
"phone":"9902",
"educational_details":[
{"board":"a","grade":"b","percentage":"21.0"},
{"board":"a1","grade":"b1","percentage":"22.0"}
]
}
Here is my following php code to decode json
$data = json_decode(file_get_contents('php://input'), true);
$fullname=$data['full_name'];
$phone=$data['phone'];
$email=$data['email'];
$nativeaddress=$data['native_address'];
$fresher=$data['fresher'];
$skills=$data['skills'];
$resumeUri=$data['resume_uri'];
$obj = $data['educational_details'];
$obj1=json_decode($obj,true);
echo "arrayval".$obj1;
Any Help would be much appreciated.. Thanks in advance :)
This was the solution as given by someone above and worked perfectly
foreach($obj as $val){
echo "<br>Board = " .$val['board']." <br>Grade = ".$val['grade'] ."<br> Percentage =".$val['percentage'];
$board=$val['board'];
$grade=$val['grade'];
$percentage=$val['percentage'];
$percentageval = floatval($percentage);
}

String compress in android and send to php server by URL and decompress in php server

I am trying to send compress string message by android device to PHP server.
This is my android code
ByteArrayOutputStream os = new ByteArrayOutputStream(string.length());
GZIPOutputStream gos = new GZIPOutputStream(os);
gos.write(string.getBytes());
gos.close();
byte[] compressed = os.toByteArray();
os.close();
and this is my php code to decode
$msg=$_GET['MsgType'];
$msg2=urldecode($msg);
print gzuncompress($msg2);
but there is error
Message: gzuncompress(): data error
i searched alot on google but didn't help if any one could help me most welcome.
You should use a post variable because url's lenght is limited to few KBs...!
You should use the following code to compress the String
public static String compressAndSend(String str, String url) throws IOException {
String body1 = str;
URL url1 = new URL(url);
URLConnection conn1 = url1.openConnection();
conn1.setDoOutput(true);
conn1.setRequestProperty("Content-encoding", "gzip");
conn1.setRequestProperty("Content-type", "application/octet-stream");
GZIPOutputStream dos1 = new GZIPOutputStream(conn1.getOutputStream());
dos1.write(body1.getBytes());
dos1.flush();
dos1.close();
BufferedReader in1 = new BufferedReader(new InputStreamReader(
conn1.getInputStream()));
String decodedString1 = "";
while ((decodedString1 = in1.readLine()) != null) {
Log.e("dump",decodedString1);
}
in1.close();
}
On PHP side use this,
<?php echo substr($HTTP_RAW_POST_DATA,10,-8); ?>
And please concern this Help manual for more information,
http://php.net/manual/en/function.gzuncompress.php

Insert blob from android to oracle

I'm working with Oracle database. I use PHP for my web service and Android as the client which will send blob data to Oracle DB. I use this code
Bitmap imageUpload = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageUpload.compress(Bitmap.CompressFormat.JPEG, 60, baos);
byte[] image_data = baos.toByteArray();
String converted_image = Base64.encodeBytes(image_data);
to decode and send it as base64 encoding, then send it to the web service with this code
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("TITLE", title));
nameValuePairs.add(new BasicNameValuePair("IMAGES", converted_image));
json = jsonParser.makeHttpRequest(url, "POST", nameValuePairs);
This is my PHP code to insert to oracle db
if(isset($_POST["TITLE"]) && isset($_POST["IMAGES"]))
{
$title = $_POST["TITLE"];
$image = $_POST["IMAGES"];
$gambar = file_get_contents($image);
$query = "INSERT INTO images (TITLE, IMAGES) VALUES (:TITLE, EMPTY_BLOB()) RETURNING IMAGES INTO :IMAGES";
$parse = oci_parse($connect, $query);
$lob_a = oci_new_descriptor($connect, OCI_D_LOB);
oci_bind_by_name($parse, ":TITLE", $title);
oci_bind_by_name($parse, ":IMAGES", $lob_a, -1, OCI_B_BLOB);
oci_execute($parse, OCI_DEFAULT);
if($lob_a->save($gambar))
{
oci_commit($connect);
$lob_a->free();
}
else
{
oci_rollback($connect);
}
}
The PHP code successfully insert the query to the oracle db, but when I see the record the blob does not show anything like this
I think the best solution to this question is to use web service, encode the picture with base64 encoding then decode it while the file transferred.

JSON exception in Android

I am trying to execute query on database in the localhost and send the JSON object to the client in android. I m not been able to know what is the problem in my code. So some one please help me on this regard.
My php code is the one where i m sending the JSON object.
php code
query executed successfully..
$row=mysql_fetch_array($result1);
$email=$row['EM'];
$pass=$row['PASS'];
$post=array("email"=>$email, "pass"=>$pass);
$posts[] = array("post"=>$post);
//echo "SUCCESS";
header('Content-type: application/json');
echo json_encode(array("posts"=>$posts));
And in android side i ve this code below;
HttpResponse response = doPost(url, kvPairs);
String responseBody=response.toString();
String temp = EntityUtils.toString(response.getEntity());
if (temp.compareTo("SUCCESS")==0)
{
Toast.makeText(this, "Working", Toast.LENGTH_LONG).show();
}
Above part executes ..
Below code throws a JSON exception
JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("posts");
no_of_obj=jArray.length();
nemail=new String[no_of_obj];
npass=new String[no_of_obj];
for (int i = 0; i < jArray.length(); i++) {
JSONObject e = jArray.getJSONObject(i);
String s = e.getString("post");
JSONObject jObject = new JSONObject(s);
Toast.makeText(context,jObject.getString("email")+":"+jObject.getString("pass") , duration).show();
nemail[i]=jObject.getString("email");
npass[i]=jObject.getString("pass");
}
In the log cat i can see : The json string must begin with "{"....
Probably you cannot do this
String s = e.getString("post");
because there is no "post" key in the array of Strings you have given,...
Try doing this,
String s = e.has("post")?e.getString("post"):null;
and then on next line keep a null check before Creating JSONObject..
Try this
$posts['data'] = $post;
//echo "SUCCESS";
header('Content-type: application/json');
echo json_encode($posts);

Categories