Php JSONArray decoding and performing Database Operation - php

I'm sending a JsonArray from my android application as this:
final JSONArray data = new JSONArray();
try{
for(int i = 0; i<contactsList.size(); i++){
JSONObject jobj = new JSONObject();
ObjectContacts ob = contactsList.get(i);
jobj.put("contactid", ob.getContact_id());
jobj.put("mobile", ob.getNumber());
data.put(jobj);
}
}
And the resulting Array that my server receive.
[
{"contactid":"3","mobile":"(545) 454-5445"},
{"contactid":"1","mobile":"(880) 939-5212"},
{"contactid":"2","mobile":"822895456165"}
]
I need to fetch mobile numbers from this array and perform a Db Operation to look if this mobile number exist or not. How can I access each mobile and perform a Query? The query will consist of looking for mobile number existence and if it's true, it will fetch the name belonging to the mobile number and finally return an array back to the mobile application in JSONArray format which will consist of contact id, mobile, status(Yes or No), name.
Time won't be an issue but sometimes the array may contain 300-400 mobile number depending on user's contact.
Update
Here's the new Php Code that I implemented:
$app->post('/getcontacts', function () use ($app) {
//Verifying the required parameters
verifyRequiredParams(array('data'));
//Creating a response array
$response = array();
//reading post parameters
$data = $app->request->post('data');
$data_array = json_decode($data);
foreach ( $data_array as $obj ) {
$res = array();
$db = new DbOperation();
$r = $db->checkContactExist($obj->mobile);
if($r){
$res["contactid"] = $obj->contactid;
$res["mobile"] = $obj->mobile;
$res["name"] = $obj->name;
$res["status"] = 'yes';
$res["image_small"] = $db->getImageSmall($obj->mobile);
} else {
$res["contactid"] = $obj->contactid;
$res["mobile"] = $obj->mobile;
$res["name"] = $obj->name;
$res["status"] = 'no';
$res["image_small"] = '';
}
}
$response["error"] = false;
$response["message"] = json_encode($res);
echoResponse(201, $response);
});
The response I get from server:
{"contactid":"3","mobile":"(943) 101-9713","status":"no","image_small":""}
While there should be three contacts, it could only read one.
If I just send the incoming data back to application through echo to check whether all the contacts is coming or not, then it works correct. Maybe in the loop I'm adding detail about only one contact.
Second Update
Have solved the issue by putting :
$final_res = array();
and in foreach loop
$final_res[] = $res;
thus sending this back:
json_encode($final_res);

That string will convert to a PHP array of objects, after using json_decode() on the string.
So this is how you process it
<?php
$json_string = '[
{"contactid":"3","mobile":"(545) 454-5445"},
{"contactid":"1","mobile":"(880) 939-5212"},
{"contactid":"2","mobile":"822895456165"}
]';
$json_array = json_decode($json_string);
foreach ( $json_array as $obj ) {
echo $obj->contactid . ' - ' . $obj->mobile . PHP_EOL;
}
Result:
3 - (545) 454-5445
1 - (880) 939-5212
2 - 822895456165
You should be able to take this and add any database access around this simple code

Related

Append php loop data to JSON object

I need looped php data in an html template so I know it has something to do with JSON however not a JSON expert and cannot find much help in searching the web.
$uniqueFranchise_id = array_unique($franchise_id);
$dataArr = '[
{
"name": "Dylan",
"page_link": "https://mypage.com/"
}
]';
foreach($uniqueFranchise_id as $franchise)
{
$sqlFranchise = "select * from franchise where franchise_id = $franchise";
$resultFranchise = $conn->query($sqlFranchise);
if($resultFranchise->num_rows > 0)
{
while($rowFranchise = $resultFranchise->fetch_assoc())
{
$dataArr = json_decode($data, TRUE);
$dataArr[] = "['name'=>'".$rowFranchise['name']."', 'page_link'=>'".$rowFranchise['page_link']."']";
//$json = json_encode($dataArr);
}
}
}
$json = json_encode($dataArr);
print_r($dataArr);
But it only appends one row. In fact it deleteds that data that's already in my dataArr and just adds one row from my loop? Maybe I'm approaching this situation completely wrong?
You set your $dataArr inside the while-loop. So each time the loop is runs, it will be overwritten. Also, it makes more sense and it's much more clear when you handle it as an array (or object) and afterwards convert it to JSON.
$dataArr = array(array('name' => 'Dylan', 'page_link' => 'https://mypage.com/'));
foreach($uniqueFranchise_id as $franchise)
{
$sqlFranchise = "select * from franchise where franchise_id = $franchise";
$resultFranchise = $conn->query($sqlFranchise);
if($resultFranchise->num_rows > 0)
{
while($rowFranchise = $resultFranchise->fetch_assoc())
{
$dataArr[] = array('name' => $rowFranchise['name'], 'page_link' => $rowFranchise['page_link']);
}
}
}
$json = json_encode($dataArr);
echo $json;
You shouldn't be building the string up by yourself, you should build the data and then JSON encode the result (comments in code)...
$dataArr = '[
{
"name": "Dylan",
"page_link": "https://mypage.com/"
}
]';
// decode existing JSON to start array
$dataArr = json_decode($data, TRUE);
foreach($uniqueFranchise_id as $franchise)
{
// Read just the data you need from the table
$sqlFranchise = "select name, page_link from franchise where franchise_id = $franchise";
$resultFranchise = $conn->query($sqlFranchise);
if($resultFranchise->num_rows > 0)
{
// Read all of the rows into an array
$newData = $resultFranchise->fetch_all(MYSQLI_ASSOC);
// Add in existing data
$dataArr = array_merge($dataArr, $newData);
}
}
// Now encode the list of elements into 1 string
echo json_encode($dataArr);
You should also look into prepared statements if this data is not trusted to stop SQL injection.

Why JSON doesn't return Lithuanian characters

I have a program that takes strings from MySQL database, creates SqlLite database with same strings and then displays them in Android application ListView.
Problem is that when I get response from PHP side it shows Lithuanian charactes as "?", but I use
JSON_UNESCAPED_UNICODE
in json_encode function. Where is the problem?
I want to mention that MySql unicode is set to "utf8_lithuanian_ci"
PHP file :
include_once 'db_functions.php';
$db = new DB_Functions();
$users = $db->getMarsrutaiCount();
$a = array();
$b = array();
if ($users != false){
$no_of_users = mysqli_num_rows($users);
while ($row = mysqli_fetch_array($users)) {
$b["id"] = $row["id"];
$b["marsrutas"] = $row["marsrutas"];
$b["pasirinkimas_id"] = $row["pasirinkimas_id"];
array_push($a,$b);
}
echo json_encode($a, JSON_UNESCAPED_UNICODE);
}
JSON Response from Android side :
ArrayList<HashMap<String, String>> usersynclist;
usersynclist = new ArrayList<HashMap<String, String>>();
// Create GSON object
Gson gson = new GsonBuilder().create();
try {
// Extract JSON array from the response
JSONArray arr = new JSONArray(response);
System.out.println(arr.length());
// If no of array elements is not zero
if(arr.length() != 0){
// Loop through each array element, get JSON object which has userid and username
for (int i = 0; i < arr.length(); i++) {
// Get JSON object
if(veiksmas == 1) {
JSONObject obj = (JSONObject) arr.get(i);
System.out.println(obj.get("id"));
System.out.println(obj.get("marsrutas"));
System.out.println(obj.get("pasirinkimas_id"));
// DB QueryValues Object to insert into SQLite
queryValues = new HashMap<String, String>();
// Add userID extracted from Object
queryValues.put("id", obj.get("id").toString());
// Add userName extracted from Object
queryValues.put("marsrutas", obj.get("marsrutas").toString());
queryValues.put("pasirinkimas_id", obj.get("pasirinkimas_id").toString());
// Insert User into SQLite DB
controller.insertMarsrutas(queryValues);

Decode Json Object from a url in php coming from a user

hey i am making an android app where user's request in the format of json . Their request will look like this..
JSONObject j = new JSONObject(createJson());
String url ="http://codemoirai.esy.es/test.php?UserDetails="+j;
Where j = {"Email":"code#gmail.com","Username":"xyz","Password":"xyz"}
This is what I will be sending to the test.php , i want to know how i can fetch this data and display it using php.
<?php
require "init1.php";
$jsonObject = $_GET["UserDetails"];
$obj = json_decode($jsonObject);
$email = $obj->Email;
$password = $obj->Password;
.......
echo $email; //Everthing i fetch from jsonObject is null. Why?
?>
ThankYou, is it correct how i am fetching in php??
In test.php you can catch the data with $_GET['UserDetails'] then decode it with json_decode($_GET['UserDetails')
Then you can iterate it with a foreach loop
Example:
if(isset($_GET['UserDetails'])) {
$details = json_decode($_GET['UserDetails']);
foreach($details as $key => $val) {
echo $key.' = '.$val;
}

android, php, parsing JSON in php file sent from android

i have this JSON
{
"count":"3",
"num":"1",
"array":[
{
"id":"a_a",
"amount":56,
"duration":"0:12",
"time":1234566,
"type":0
},
{
"id":"a_a",
"amount":56,
"duration":"0:12",
"time":1234566,
"type":1
}
]
}
created it in android and send it by **HttpPost**
, i've tried a lot of ways to get the data in the php, my php file is this:
<?php
$response = array();
//$json_data = json_encode(stripslashes($_POST['jsonarray']))
$josn = file_get_contents("php://input");
$json_data = json_decode($josn,true);
$count = $json_data->{'count'};
$num = $json_data["num"];
$response["data"]=$count;
$response["data2"]=$num;
// echoing JSON response
echo json_encode($response);
?>
but $count and $num always returns null, any help please, and thanks.
$json_data = json_decode($josn,true);
this returns an array, not an object (which you are using later in the code). Use this to convert the json string to an object:
$json_data = json_decode($josn);
Or you could just use arrays, in which case your code should look like:
<?php
$response = array();
//$json_data = json_encode(stripslashes($_POST['jsonarray']))
$josn = file_get_contents("php://input");
$json_data = json_decode($josn, true); // using true to get array
$count = $json_data["count"]; // accessing array values as normal
$num = $json_data["num"]; // accessing array values as normal
$response["data"] = $count; // instead of setting $count first you could just add
$response["data2"] = $num; // the json_data array values directly to the response array
// echoing JSON response
echo json_encode($response);

Retrieve all values in my loop and format it to json

I'm trying to build a page which queries my database and then formats output so another webservice/page can access the data.
Ideally I wanted to explore having the data in JSON format, but that is not working. The other problem I have which is more major than the JSON not working is, if I have 3 records in $reportsResult, only the last one is displayed.
Anyone with some help please. Oh do I also need to print_r for the external webpage to retrieve the data or is there a better way?
class Pupil {
public $FirstName = "";
public $LastName = "";
}
foreach($reportsResult->getRecords() as $reportRecord) {
$Pupil = new Pupil();
$Pupil->FirstName = $reportRecord->getField('FName');
$Pupil->LastName = $reportRecord->getField('SName');
}
json_encode($Pupil);
OK managed to figure out how how to get all records from the loop, but its still not displaying in json format when I do a print_r - am I missing something?
$AllPupils = array();
foreach($reportsResult->getRecords() as $reportRecord)
{
$Pupil = new Pupil();
$Pupil->FamID = $reportRecord->getField('FName');
$Pupil->ChildName = $reportRecord->getField('SName');
array_push($AllPupils, $Pupil);
}
json_encode($AllPupils);
Everytime your foreach loop starts again, it will override your $Pupil variable.
Try an array instead:
$Pupil = array()
$i = 0;
foreach($reportsResult->getRecords() as $reportRecord) {
$Pupil[$i] = new Pupil();
$Pupil[$i]->FirstName = $reportRecord->getField('FName');
$Pupil[$i]->LastName = $reportRecord->getField('SName');
$i++;
}
echo json_encode($Pupil);
Edit: mikemackintosh's solution should also work and could be a little bit faster (depending on the size of your foreach loop).
To display the results you need to echo your data (not only json_encode).
You will probably run into issues since json_encode wont handle the whole object. for that, you may want to serialize the $Pupil object.
Something like below may work for you though. It will assign the values to a returned array, which will allow json_encode to execute gracefully:
class Pupil {
public $FirstName = "";
public $LastName = "";
public function getAttr(){
return array("FirstName" => $this->FirstName, "LastName" => $this->LastName);
}
}
$json = array();
foreach($reportsResult->getRecords() as $reportRecord) {
$Pupil = new Pupil();
$Pupil->FirstName = $reportRecord->getField('FName');
$Pupil->LastName = $reportRecord->getField('SName');
$json[] = $Pupil->getAttr();
}
echo json_encode($json);
I am not sure why you have that class defined, but you know what in your for each have something like
foreach ($reportsResult->getRecords() as $key => $record) {
$data[$key]['firstname'] = $record->getField('Fname');
$data[$key]['lastname'] = $record->getField('Sname');
}
And then you can check the final array using print_r
and while output you can simply do a print json_encode($data) and it will give you a json string of all the items in the data array.
In php (at least), json_encode takes an array as parameter.
Therefore you should add a constructor to your class
function __construct($first, $last)
{
this.$FirstName = $first;
this.$LastName = $last;
}
and one for getting the full name as an array, ready to be jsoned
function getNameArray()
{
$nameArray = array();
$nameArray['firstName'] = this.$FirstName;
$nameArray['lastName'] = this.$LastName;
return $nameArray;
}
then in that foreach you build another array with all the pupils
$pupils = array();
foreach (bla bla)
{
$first = $reportRecord->getField('FName');
$last = $reportRecord->getField('SName');
$Pupil = new Pupil($first, $last);
array_push($pupils, $pupil.getNameArray());
}
finally, you have everything preped up
json_encode($pupils);
I'm sure there's other ways to debug your stuff, I use print_r mainly also.

Categories