I've done a long search before posting, none of solutions work for me.
I'm creating an Android application, using JSON and PHP;
PHP
/**
*
LOT OF USELESS THING
*
*/
//Attributing values of $OUTPUT
$q=mysql_query($query);
if (!$q)
die(mysql_error()); // You'll be notified if there's any syntax error in your query.
$OUTPUT = array(array());
if ($q && #mysql_num_rows($q) > 0) {
// looping through all results
// products node
while($e=#mysql_fetch_assoc($q)){
if (!empty($e['title'])){
$u = Array();
$u['id'] = mb_convert_encoding($e['id'], 'UTF-8');
$u['title'] = mb_convert_encoding($e['title'], 'UTF-8');
$u['location_search_text'] = mb_convert_encoding($e['location_search_text'], 'UTF-8');
$OUTPUT[] = $u;}
//echo "<br>************<br>";*/
//$OUTPUT[] = $e;
}
}
print(json_encode($OUTPUT));
Now, this is the output of json:
[[],{"id":"796","title":"ANSEJ ORAN \/Agence de Soutien \u00e0 l'Emploi des Jeunes d'Oran","locat ...etc
If you see, there's a []; an empty array, which of course causes me problem in Java, when parsing data with
JSONArray jArray = new JSONArray(result);
Occuring me a JSONExcpetion:
Error parsing data org.json.JSONException: Value [] at 0 of type org.json.JSONArray cannot be converted to JSONObject
Not $OUTPUT = array(array()); - this create empty array inside
But $OUTPUT = array();
Related
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.
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);
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
This question already has answers here:
JSON encode MySQL results
(16 answers)
Closed 1 year ago.
I've spent a couple of hours looking through several the similar answers before posting my problem.
I'm retrieving data from a table in my database, and I want to encode it into a JSON. However, the output of json_encode() is only valid when the table has one single row. If there is more than one row, the test at http://jsonlint.com/ returns an error.
This is my query:
$result = mysql_query($query);
$rows = array();
//retrieve and print every record
while($r = mysql_fetch_assoc($result)){
$rows['data'] = $r;
//echo result as json
echo json_encode($rows);
}
That gets me the following JSON:
{
"data":
{
"entry_id":"2",
"entry_type":"Information Relevant to the Subject",
"entry":"This is my second entry."
}
}
{
"data":{
"entry_id":"1",
"entry_type":"My Opinion About What Happened",
"entry":"This is my first entry."
}
}
When I run the test at http://jsonlint.com/, it returns this error:
Parse error on line 29:
..."No comment" }}{ "data": {
---------------------^
Expecting 'EOF', '}', ',', ']'
However, if I only use this first half of the JSON...
{
"data":
{
"entry_id":"2",
"entry_type":"Information Relevant to the Subject",
"entry":"This is my second entry."
}
}
... or if I only test the second half...
{
"data":{
"entry_id":"1",
"entry_type":"My Opinion About What Happened",
"entry":"This is my first entry."
}
}
... the same test will return "Valid JSON".
What I want is to be able to output in one single [valid] JSON every row in the table.
Any suggestion will be very much appreciated.
The problem is you're spitting out separate JSON for each row, as opposed to doing it all at once.
$result = mysql_query($query);
$rows = array();
//retrieve and print every record
while($r = mysql_fetch_assoc($result)){
// $rows[] = $r; has the same effect, without the superfluous data attribute
$rows[] = array('data' => $r);
}
// now all the rows have been fetched, it can be encoded
echo json_encode($rows);
The minor change I've made is to store each row of the database as a new value in the $rows array. This means that when it's done, your $rows array contains all of the rows from your query, and thus you can get the correct result once it's finished.
The problem with your solution is that you're echoing valid JSON for one row of the database, but json_encode() doesn't know about all the other rows, so you're getting a succession of individual JSON objects, as opposed to a single one containing an array.
You need to change your PHP code into something like this:
$result = mysql_query($query);
$rows = array();
//retrieve every record and put it into an array that we can later turn into JSON
while($r = mysql_fetch_assoc($result)){
$rows[]['data'] = $r;
}
//echo result as json
echo json_encode($rows);
I think you should do
$rows = array();
while($r = mysql_fetch_assoc($result)){
$rows[]['data'] = $r;
}
echo json_encode($rows);
echo should be placed outside of the loop.
I was trying the same in my PHP, so I came whit this...
$find = mysql_query("SELECT Id,nombre, appaterno, apmaterno, semestre, seccion, carrera FROM Alumno");
//check that records exist
if(mysql_num_rows($find)>0) {
$response= array();
$response["success"] = 1;
while($line = mysql_fetch_assoc($find)){}
$response[] = $line; //This worked for me
}
echo json_encode($response);
} else {
//Return error
$response["success"] = 0;
$response["error"] = 1;
$response["error_msg"] = "Alumno could not be found";
echo json_encode($response);
}
And, in my Android Class...
if (Integer.parseInt(json.getString("success")) == 1) {
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
if (!value.equals(1)) {
JSONObject jsonArray = (JSONObject) value;
int id = jsonArray.getInt("Id");
if (!db.ExisteAlumo(id)) {
Log.e("DB EXISTE:","INN");
Alumno a = new Alumno();
int carrera=0;
a.setId_alumno(id);
a.setNombre(jsonArray.getString("nombre"));
a.setAp_paterno(jsonArray.getString("appaterno"));
a.setAp_materno(jsonArray.getString("apmaterno"));
a.setSemestre(Integer.valueOf(jsonArray.getString("semestre")));
a.setSeccion(jsonArray.getString("seccion"));
if(jsonArray.getString("carrera").equals("C"))
carrera=1;
if(jsonArray.getString("carrera").equals("E"))
carrera=2;
if(jsonArray.getString("carrera").equals("M"))
carrera=3;
if(jsonArray.getString("carrera").equals("S"))
carrera=4;
a.setCarrera(carrera);
db.addAlumno(a);
}
}
} catch (JSONException e) {
// Something went wrong!
}
}
I must have spent 15 hours on this issue. Every variation discussed above was tried. Finally I was able to get the 'standard solution' working. The issue, very oddly, appears to be this:
When the interval is set beyond 14 hours, json appears to be unable to parse it. There must be a limit to JSON.
$sql= "SELECT cpu_name, used, timestamp FROM tbl_cpu_use WHERE timestamp>(NOW() - INTERVAL 14 HOUR) ORDER BY id";
$result=mysql_query($sql);
if ($result){
$i=0;
$return =[];
while($row = mysql_fetch_array($result, MYSQL_NUM)){
$rows[] = $row;
}
echo json_encode($rows);
}else{
echo "ERROR";
}
When converting a MongoCursor to PHP I use this script. Which was presented here
StackOverflowSO
using the upper method, the structure is same but _id is whereas using the lower script which yields the below included result.
Unfortunately, this results in the actual object being embedded into an array with the _id from Mongo. Like this :
`4eefa79d76d6fd8b50000007 = {
"_id" = {
"$id" = 4eefa79d76d6fd8b50000007;
};
longText = "Error Description";
nCode = dee29fd7e15ce4ab2d3f7dfa7c5d8fc44b27501ad00908771128c920ef276154;
nStatus = Process;
nText = "E12345";
nVType = Type1;
pId = {
"$id" = 4eefa79676d6fd8b50000003;
};
pushDate = "2011-12-20+06%3A07%3A41";
updateFlag = 1;
};`
Since I am passing this object to another service for processing the _id is not known.
How can I convince the PHP Driver to parse the object properly?
Basically what I did was this.
return json_encode(iterator_to_array($cursor));
But this created the aforementioned object which is not what I needed.
I solved it in this way.
$i=0;
foreach($cursor as $item){
$return[$i] = array(
'_id'=>$item['_id'],
'nCode'=>$item['nCode'],
'pId'=>$item['pId'],
'nText'=>$item['nText'],
'longText'=>$item['longText'],
'nStatus'=>$item['nStatus'],
'nVType'=>$item['nVType'],
'pushDate'=>$item['pushDate'],
'updateFlag'=>$item['updateFlag'],
'counter' => $i
);
$i++;
}
return json_encode($return);
If you result is big in order to save RAM you could try this more efficient method:
function outIterator($iterator, $resultName='results')
{
// Efficient MongoCursor Iterator to JSON
// instead of encoding the whole result array to json
// process each item individually
// in order to save memory by not copying the data multiple times
//Start Json Output
header('Content-Type: application/json');
echo '{' . $resultName . ': ['
//Output each item as json if there are results in the iterator
if ($iterator->hasNext()){
foreach ($iterator as $item)
{
echo json_encode ($fixeditem);
if ($iterator->hasNext()) echo ', ';
}
}
//end Json output
echo ']}';
}
$results = $db->collection->find();
outIterator($results);