MySql PHP Select JSON value - php

I have this SQL query.
$sql = "SELECT playerjson FROM `clans` WHERE playercount > ? AND level > ? AND score > ?";
$selectstmt = $con->prepare($sql);
$selectstmt->bind_param('iii',$playercountvar,$levelvar,$scorevar);
$selectstmt->execute(); //execute select statement
$result = $selectstmt->get_result(); //get select statement results
playerjson is a large JSON Array.
[
{
"avatar":{
"userId":253404325847,
"currentHomeId":253404325847,
"userName":"enal",
"role":"Member",
"level":62,
"league":8,
"trophies":1707,
"donatedTroops":0,
"receivedTroops":0,
"clanRank":1,
"lastClanRank":2,
"inWar":1
}
},
{
"avatar":{
"userId":158925253577,
"currentHomeId":158925253577,
"userName":"Valen kamja",
"role":"Leader",
"level":54,
"league":8,
"trophies":1693,
"donatedTroops":1054,
"receivedTroops":2131,
"clanRank":2,
"lastClanRank":3,
"inWar":1
}
},
{
"avatar":{
"userId":296357929514,
"currentHomeId":296357929514,
"userName":"\u0645\u064c\u0648\u0646\u0633\u062a\u064d\u0631502",
"role":"Member",
"level":59,
"league":7,
"trophies":1568,
"donatedTroops":0,
"receivedTroops":0,
"clanRank":3,
"lastClanRank":0,
"inWar":1
}
},
{
"avatar":{
"userId":283468864924,
"currentHomeId":283468864924,
"userName":"tolzz",
"role":"Co-Leader",
"level":64,
"league":7,
"trophies":1312,
"donatedTroops":34,
"receivedTroops":456,
"clanRank":4,
"lastClanRank":4,
"inWar":1
}
},
{
"avatar":{
"userId":257703167804,
"currentHomeId":257703167804,
"userName":"hailery",
"role":"Co-Leader",
"level":58,
"league":6,
"trophies":1219,
"donatedTroops":21,
"receivedTroops":404,
"clanRank":5,
"lastClanRank":5,
"inWar":1
}
},
{
"avatar":{
"userId":210456177319,
"currentHomeId":210456177319,
"userName":"chey lie",
"role":"Co-Leader",
"level":79,
"league":0,
"trophies":1101,
"donatedTroops":0,
"receivedTroops":0,
"clanRank":6,
"lastClanRank":6,
"inWar":0
}
}
]
What I want to do is just store the userid and currenthomeid and store them in an array which will be in a parent array...
Because from that I will need to get the child array and pass those one by one as parameters in a url. explode wouldn't work with this would it?
How would I go about achieving this? Also I need a way to improve the SQL Statement so that I don't retrieve the entire JSON like that as it could take longer?

Decode the result string and iterate over it as stdClasses :
$json = json_decode($result);
$parent = array();
foreach($json as $item) {
$parent[] = array('userId' => $item->avatar->userId, 'currentHomeId' => $item->avatar->currentHomeId);
}
echo '<pre>';
print_r($parent);
echo '</pre>';
will produce :
Array
(
[0] => Array
(
[user] => 253404325847
[currentHomeId] => 253404325847
)
[1] => Array
(
[user] => 158925253577
[currentHomeId] => 158925253577
)
etc. To pass $parent as a URL string you could simply use json_encode to stringify it :
$url = '?values='.json_encode($parent);
gives ?values=[{"user":253404325847,"currentHomeId":253404325847},{"user":158925253577," etc...
This will automatically be escaped, you can read the array back in javascript clientside with
var value = window.location.href.split('?values=')[1],
array = JSON.parse(unescape(value));
console.log(array);
you now have the array as JSON objects clientside. There is many ways you could do this. This was just a quick suggesion.

What you have is a json encoded atrray. So use json_decode() to decode it.
$arr1 = json_decode($result);
foreach ($arr1 as $row) {
echo $row->avatar->userId."-------".$row->avatar->currentHomeId."<br>" ;
}

Related

Not updating data on json file but my code is correct via PHP

I'm a newbie here so please be with. I'm pretty sure that my code and syntax is correct.
This is my json file
{"data":
[
{"label":"Signed-in Client","value":2
}
]
}
This is my php code
<?php
$conn=mysqli_connect("localhost", "root","","something");
$res1 = mysqli_query($conn, "SELECT * FROM tbl_pet_owner ORDER BY pet_owner_id");
$max1 = mysqli_num_rows($res1);
$jsonString = file_get_contents('data.json');
$data1 = json_decode($jsonString, true);
foreach ($data1['data'] as $key )
{
if ($key[0]['label'] == "Signed-in Client")
{
$data1['value'] = $max1;
}
}
$newJsonString = json_encode($data1);
file_put_contents('data.json', $newJsonString);
?>
but when I refresh, it doesn't update with the max count of my query. I hope you'd help me. This is for my thesis
It seems to me that the problem is connected with the way how you traverse the data.
For example in foreach ($data1['data'] as $key ), $key is already an associative array (e.g., array("label" => "Signed-in Client", "value" => 2)), so instead of $key[0]['label'], one should use just $key['label'].
Also, when you want to modify the 'value', one has to access the same associative array, not the original variable $data1.
One way to achieve this would be as shown below. In that example the array $data1['data'] is traversed using references (&$key). Note that one should then unset this variable after the foreach block to break its association with the last element of the array being traversed.
<?php
$max1 = 100;//just an example
$jsonString = file_get_contents('data.json');
$data1 = json_decode($jsonString, true);
foreach ($data1['data'] as &$key )
{
print_r($key);
if($key['label'] == "Signed-in Client")
{
$key['value'] = $max1;
}
}
unset($key);
print_r($data1);
/* gives:
Array
(
[data] => Array
(
[0] => Array
(
[label] => Signed-in Client
[value] => 100
)
)
)
*/
//$newJsonString = json_encode($data1);
//file_put_contents('data.json', $newJsonString);
?>

json_encode in PHP is not returning any results

I have a PHP script that is retrieving some data from my database, and I want to encode it in json for processing in my Android app. I want the results to be like this:
{
"part": [
{
"partNo": "value",
"partName": "value",
"shortDesc": "value",
"longDesc": "value",
"image": "value"
},
{
"partNo": "value",
"partName": "value",
"shortDesc": "value",
"longDesc": "value",
"image": "value"
}
],
"success": 1
}
I am using the following PHP script.
// array for JSON response
$response = array();
// execute query based on specified user input
$result = mysql_query($sql) or die(mysql_error());
// check to see if results were found
if (mysql_num_rows($result) > 0) {
//create a part array in $response to hold the part details
$response['part'] = array();
while ($row = mysql_fetch_array($result)) {
//create an array for the part details
$part = array();
$part['partNo'] = $row['partNo'];
$part['partName'] = $row['partName'];
$part['shortDesc'] = $row['shortDesc'];
$part['longDesc'] = $row['longDesc'];
$part['image'] = "data:image/jpeg;base64,".base64_encode($row['image']);
// put the array results for a single part in $response
array_push($response['part'], $part);
}
// add the code for success to $response
$response['code'] = 1;
// and send it in json
echo(json_encode($response));
//print_r($response);
//print_r(json_encode($response));
} else {
//no results found
$response['code'] = 0;
$response['message'] = "No part found!";
echo json_encode($response);
}
?>
I am not getting any response with echo (json_encode($response)); or print_r(json_encode($response));. But when I do print_r($response);, I am getting a response!
Array ( [part] => Array ( [0] => Array ( [partNo] => value [partName] => value [shortDesc] => value [longDesc] => value [image] => data:image/jpeg;base64,/9j/4QAYRXhpZgAAS.../9k= ) ) [code] => 1 )
Can anyone shed some light on this? Why is it not working with json_encode?
Just use to return the $response in json format:
header('Content-type: application/json');
echo json_encode($response);

MySQL to JSON (For use with NVD3.js)

I'm trying to export the MySQL table below:
id, asof, value
abc, 2013-06-30, 36000000
abc, 2013-12-31, 48000000
abc, 2014-01-31, 51000000
abc, 2014-02-28, 56000000
xyz, 2013-06-30, 26000000
xyz, 2013-12-31, 33000000
xyz, 2014-01-31, 33000000
xyz, 2014-02-28, 36000000
into the following json format for use in the nvd3.js charts:
[
{
"key" : "abc" ,
"values" : [ [ 2013-06-30, 36000000] , [ 2013-12-31, 48000000] , [ 2014-01-31, 51000000] , [ 2014-02-28, 56000000]
},
{
"key" : "xyz" ,
"values" : [ [ 2013-06-30, 26000000] , [ 2013-12-31, 33000000] , [ 2014-01-31, 33000000] , [ 2014-02-28, 36000000]
}
]
I'm sure this is a newbie question but I'm struggling with it. Any guidance would be much appreciated!
Edit:
I've currently been trying to use an array and while statement but have not been able to figure out how to modify the array to so that it can output to the correct json format.
$query= mysqli_query($db,"SELECT id, asof, value
FROM table;"
);
if ( ! $query) {
echo mysqli_error();
die;
}
$rows = array();
while($r = mysqli_fetch_assoc($query)) {
$rows[] = $r;
}
print json_encode($rows);
Probably the most straightforward way of doing this is simply creating a multidimensional array, filling it with data obtained from database and then using json_encode to create a JSON string, which is then sent to the client.
Here is a simple example of a function which will accept an array of items and return a JSON string in the expected format. For simplicity, it is assumed that data was is a 2D array with three columns, but you should modify it to use the format returned by a database query.
function convert($data) {
$intermediate = array();
// This intermediate steps is used just to group all rows with
// the same key
foreach($data as $item) {
list($key, $date, $value) = $item;
$intermediate[$key][] = array($date, $value);
}
$output = array();
foreach($intermediate as $key => $values) {
$output[] = array(
'key' => $key,
'values' => $values
);
}
return $output;
}
Since you're getting data from database, variable $item inside the first foreach statement might actually be an associate array, so you'll have to write something like $item['key'] to get data for columns in the current row.
If you want to use mysqli_fetch_assoc, then you might try calling the function convert in the following way:
$conn = mysqli_connect('', '', '')
$query = 'SQL you wish to execute'
$result = mysqli_query($conn, $query)
if($result) {
$jsonData = convert($result);
}
However, function itself needs a little bit changing
function convert($result) {
$intermediate = array();
while($item = mysqli_fetch_assoc($result)) {
$key = $item['id'];
$date = $item['asof'];
$value = $item['value'];
$intermediate[$key][] = array($date, $value);
}
// The rest of the function stays the same
}

json_encode particular part of array

$array = array("Real" => array("Alonso","Zidan"),"Inter" => "Zanetti", "Roma" => "Toti");
$json=json_encode($array);
echo $json
By this way I am reading all the data, but how can I read the data of
only Real or Inter?
For example, if it is json_decoded I can do so:
For Inter:
echo $array['Inter'];
For Real:
foreach($array["Real"] as $real){
echo $real."<br>";
}
How can I do the same with json_encode()?
json_encode() returns a string, so you can't access its parts without parsing the string. But you can do the following instead:
echo json_encode($array['Inter']);
As I understand your question you need to output the json`d object.
Input
$input = '{"Real":["Alonso","Zidan"],"Inter":"Zanetti","Roma":"Toti"}';
In php:
// Second true is for array return, not object)
$string = json_decode($input, true)
echo $string['Inter'];
In Javascript (jQuery):
var obj = jQuery.parseJSON(input);
if (obj != undefined) {
echo obj['Inter'];
}
UPD:
If you need to get an json in all arrays you need to make follow:
$array = array("Real" => array("Alonso","Zidan"),"Inter" => "Zanetti", "Roma" => "Toti");
foreach($array as $key => $value) {
$array[$key] = json_encode($value);
}
After this code all variables in array will be json`ed and you can echo them in any time

Getting Twitter followers with JSON in PHP?

I can get Tweets of users quite easily using PHP and JSON, but as soon as I use it to get a list of followers, I get errors. Both use JSON to return the values.
The code is:
$jsonurl = "https://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name=mooinooicat";
$contents = file_get_contents($jsonurl);
$results = json_decode($contents, true);
echo "<pre>";
print_r($results);
echo "</pre>";
This gives me the following array:
Array
(
[next_cursor] => 0
[ids] => Array
(
[0] => 31085924
[1] => 53633023
[2] => 18263583
)
[previous_cursor] => 0
[next_cursor_str] => 0
[previous_cursor_str] => 0
)
How do I get the values of next_cursor and previous_cursor and how do I loop just through the ids array?
I want to parse the results for reading into a database.
you are not using the correct api try something like this
function fetch_twitter_count($user) {
if ($json = file_get_contents("http://api.twitter.com/1/users/show.json?screen_name=$user")) {
if(empty($json)) return 0;
$json = json_decode($json['body'], true);
return number_format(intval($json['followers_count']));
}
return 'API Error';
}
have not tested but should do what you want however keep inmind that you will want to use some sort of caching
Thanks for all the answers without examples...
I finally managed to figure it out using the example from Getting values from a single array
Here is the code:
foreach ( $results as $result ) {
if ( is_array( $result ) ) {
foreach ( $result as $sub_result ) {
// You can store this value in a variable, or output it in your desired format.
echo $sub_result . "<br />";
}
} else {
echo $result . "<br />";
}
}

Categories