Last comma in JSON Array to android - php

I am having a problem with the last comma when I am using PHP echoing JSON Array to android
Here is my code
If ($commentResult>0)
echo "[";
{
while ($row = mysql_fetch_array($commentResult)) {
echo json_encode($row).",";
}
echo "]";
Android can't read this, it printed out JSONException:Vale at 3 is null

Why are you trying to re-invent the wheel? If you want to give an entire array then put json_encode over the entire array instead of trying to manually build it.
$comments=array();
if($commentResult>0){
while($row=mysql_fetch_array($commentResult)){
$comments[]=$row;
}
}
echo json_encode($comments);
*Also, a side tip, don't use mysql_ functions. Instead use PDO or mysqli, which are better supported and get you rid of this whole while($row) business.*

The way you form you json is really strange. Don't know if it's an issue but you can try it in a more clean way:
if ($commentResult) {
for ($data = array(); $row = mysql_fetch_array($commentResult); $data[] = $row);
echo json_encode($data);
}

What ever JSON you are generating using PHP, Just verify that in http://jsonlint.com/. if output is wrong it wont validate other wise its OK from PHP side.

Related

Json_encode returns json cells as string

I've got a database structure like this.
I'm willing to get row as a json object for Json.net.
My php code is this
$check_query = mysqli_query($conn, "select * from users where name = '$name' and password = '$pass'");
$rows = array();
while($r = mysqli_fetch_assoc($get_query)) {
$rows[] = $r;
}
if(count($rows) > 0) {
echo json_encode($rows[0]);
}
I'm getting json as this.
{"unique_id":"pcg9sy26","name":"w","password":"w","mail":"alpsavrum#gmail.com","age":18,"locale":"Turkey","city":"Istanbul","subscriptions":"[\"electronics\", \"vacations\"]","history":null,"token":"12562f39b990da0433d7be71992ed634"}
As you can see, subscriptions value is string. I need it to be array as it seems.
{"unique_id":"pcg9sy26","name":"w","password":"w","mail":"alpsavrum#gmail.com","age":18,"locale":"Turkey","city":"Istanbul","subscriptions":[\"electronics\", \"vacations\"],"history":null,"token":"12562f39b990da0433d7be71992ed634"}
Is there any way to achieve this. ?
Thanks a lot !
The way you're retrieving that data is giving you the JSON value as a string. Storing it as JSON in the database is a good idea if it's actually JSON data, but the mysqli driver will not automatically de-serialize it for you. If you want that sort of behaviour you'll need to use an ORM.
When you're having trouble with double encoding, check with var_dump to see what you're actually working with. That would reveal the subscriptions key contains a JSON string, not an array as expected.
What you'll have to do is manually de-serialize it prior to JSON encoding:
if (isset($r['subscriptions'])) {
$r['subscriptions'] = json_decode($r['subscriptions']);
}
$rows[] = $r;
You will need to do this for any and all JSON encoded fields your results might have.
This way you're JSON encoding a proper PHP data structure and not one that's part PHP and part JSON string.
Try json decode function in whatever language you are reading it.
Decode the JSON response and then print it

Reference specific row's column value from array

I have read a-lot of answers on this but they don't seem to be working.
I have the following code:
$amountoflikes=mysql_query("SELECT * FROM `uc_likes` WHERE `dwable` = '372'");
This returns the following:
If I wanted to echo the value of dwable in the 2nd row for instance (not involving the initial query).
I've tried:
while($row3 = mysql_fetch_assoc($amountoflikes)){
$json[] = $row3;
}
echo json_encode($json);
But this returns null.
I'm currently using PHP 5.5 (native).
I'm not using MySQLi or MySQL PDO.
Can someone tell me where I'm going wrong. Ideally I'd prefer not to use a loop but I don't know if that's possible.
Thanks!
Try declaring $json as an array above the while:
$json = array();
declare your array as follows
$json = array();
and see if you have results before your result
if ($amountoflikes)
{
while(){...}
}

Passing PHP array to Javascript via GET

I'm trying to pass an array to Javascript after it has sent a GET request to PHP.
Sending and retrieving the data works perfectly but I couldn't find anything about passing the data back as an array like this:
<?php
$result = mysql_query('blablabla');
//converting $result to an array?
echo $result_as_javascript_array;
?>
<script>
$('result').innerHTML = httpGet.responseText
</script>
Convert the data you get from MySQL to JSON. First build a "normal" PHP array as you would normally do, then pass it through the json_encode() function and return it.
On the client you have to parse the JSON string into a JS array or object. See this SO question for details: Parse JSON in JavaScript?
And please use something else for accessing MySQL. The extension you are using is basically obsolete: http://si1.php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated
you should use json_encode, which works fine, when directly assigning output to a javascript variable
<?php
$result = mysql_query('blablabla');
//first convert result to an associative array
$myarray = array();
while($fetch = mysql_fetch_assoc($result)){
$myarray[]=$fetch;
}
//converting $result to an array?
echo "<script>";
echo "var myArray = ".json_encode($myarray).";";
echo "</script>";
?>
<script>
//now you can use myArray global javascript variable
$('result').innerHTML = myArray.join(",");
</script>
You are looking for json_encode.
Use json_encode like this:
<?php
$result = mysql_query('blablabla');
//converting $result to an array?
echo json_encode($result);
?>
You probably won't want to put the response text right into the innerHTML of your element though unless you are wanting to display the json text in the element.
$arr = array();
while ($row = mysql_fetch_array($result)) {
$arr[] = $row;
}
echo $arr;
However, mysql_ is deprecated, use mysqli instead.
If you want to pass it as JSON, use this:
echo json_encode($arr);

PHP, JSON, and MySQL

What is the easiest way to retrieve data from the database, and convert the data to a JSON String?
Is there any kind of helper class? or am I supposed to loop through the columns in my dataset to create the JSON string?
You can use the json_encode function to convert a native PHP array or stdClass object to it's corresponding JSON representation:
$result = $db->query('SOME QUERY');
$set = array();
if($result->num_rows) {
while($row = $result->fetch_array()) {
$set[] = $row;
}
}
echo json_encode($set);
Make an array from mySQL, and json_encode() it
Yes, use PHP's functions to handle JSON encoding.
Here's an example I got from this SO question:
$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
Have you seen the json_encode() function? It takes an array as input and outputs JSON. So the most basic would be a two-dimensional array representing your table as input to json_encode
If you use the json_encode function then you're depending on somebody else's interpretation of the right way to format the json. Which means that you might come out with weird json, or have to contort your classes in evil ways to make the json come out right.
Just something to think about.

JSON_encode adding too much stuff! How do I filter it all out?

I'm calling in values using PHP to cURL a site's API. I'm able to pull the data in and put into an array just fine, but when using JSON, one of the attributes ($title) comes back with too much data.
For example, if I just do
echo $new_array[27]['title'];
-> I get "Event Name" but if I do
echo json_encode($new_array[27]['title']);
-> I get {"#attributes":{"abc_id":"8"},"0":"Event Name"}
I want to use JSON as this works with something else I'm doing, but is there a way I can strip out the {"#attributes":{"abc_id":"8"},"0": part leaving just the "Event Name" as a string by itself?
Try:
$json = $new_array[27]['title'];
echo json_encode($json);
I'm not sure what you have in your array there, so these are a guess!
You could try:
unset($new_array[27]['title']['#attributes']);
Or:
$a = array();
foreach($new_array[27]['title'] as $arr) {
$a[] = $arr->__toString();
}
echo json_encode($a);

Categories