How to get data from json_encoded data from mysql in php? - php

I am storing data in json format in mysql database table column like
table A
column-user_details
"{\"name\":\"sadasfsf\",\"phone\":\"7896521747\",\"address_1\":\"dvgsdsd\",\"state_name\":\"g\",\"city_name\":\"sdgds\",\"zip_code\":\"ghdfh\"}"
I am fetching data like
json_decode($variable, true);
<?php echo $variable['name'];?>
However I am getting error like
Illegal string offset 'name'

the first parameter of json_decode is not a parameter passing by reference, so if you want to get the json code as php array, you mast adding the result of json_decode into a variable.
<?php
$variable = "{\"name\":\"sadasfsf\",\"phone\":\"7896521747\",\"address_1\":\"dvgsdsd\",\"state_name\":\"g\",\"city_name\":\"sdgds\",\"zip_code\":\"ghdfh\"}";
$array = json_decode($variable, true);
echo $array['name'];
NB: json_decode() is a php code, so you must use it after <?php tag, not outside of it

Related

saving array to db but is serialized as a string

I'm saving an array to the db but when I do the array is getting quotes around it from the start to end
e.g
"[{"id":"1","country":"New Zealand","shipping_rate":"1"},{"id":"2","country":"Australia","shipping_rate":"2"}]"
the array shouldn't be quoted at the start and the end when saving but this is happening. When I check my model on the shipping field that is an array I tried to trim it but it's says it can't because it says it's an array, so the problem is when it's being saved to the db for that field
The array should just look like this when being saved unquoted
[{"id":"1","country":"New Zealand","shipping_rate":"1"},{"id":"2","country":"Australia","shipping_rate":"2"}]
mysql doesn't save arrays, it saves strings. When saving an array it is by design that it serializes the array into a string.
If you are using MySql 5.7.8 or later you can use the JSON data type.
https://dev.mysql.com/doc/refman/5.7/en/json.html
You can't save an array in the mysql directly it will throws exception, you should convert it in a string(use json_encode()) and save it in mysql in either varachar/text type field.
Again when you get the data from db, convert it in an array(use json_decode()) and then use it.
u must convert json string to array :
<?php
$json_string= '[{"id":"1","country":"New Zealand","shipping_rate":"1"},{"id":"2","country":"Australia","shipping_rate":"2"}]';
$array = json_decode($json_string,true);
?>
then make a loop with foreach and enter a query in foreach :
<?php
foreach($array as $data){
$id = $data['id'];
$country = $data['country'];
$save= mysql_query("insert into your_database values("$id", "$country")";
}
?>
i home this help

how to fetch json fom url in php

I am trying to make a php page tp print json data for this i m using one paraeter for which i needed to fetch json from another url.I used the code given in other stackoverflow ans but it always giving 0.I tried everything but it always giving 0.My php code is:
<?php
if(isset($_POST['add']))
{
require_once('loginConnect.php');
$bookname=$_POST['bookname'];
$url = "http://example/star_avg.php?bookName=$bookname";
$json = file_get_contents($url);
$json_data = json_decode($json,TRUE);
echo 'data' + $json_data->results[0]->{'num'};
?>
My json data from other url is:
{"result":[{"avg":"3.9","num":"3"}]}
You see 0 printed because you're performing an addition + between the string data and a non-existent property. In PHP, to concatenate strings, do not use +; instead, use the dot . operator
In addition, because you're using true as the 2nd parameter to json_decode, what you get back is an array of arrays. Use the array notation [] rather than the object notation -> to access members.
$json_data = json_decode($json,TRUE);
$num = $json_data['result'][0]['num']; //<- array notation
echo 'data: '.$num; //prints data: 3
Live demo

Use php variable index for retriving data from json

This is my json.
In php
$json = json_decode($finalAppData, true); // decode the JSON into an associative array
//suppose this is $link = ['appInfo']['items'][0]['screen']['items'][0]['screen']['items'][0];
This code is not working.
echo $json .$link."['screen']['menuHeader']";
produces output as
Array['appInfo']['items'][0]['screen']['items'][0]['screen']['items'][0]['screen']['menuHeader'].
but i want text value that can be seen if i use simply
echo $json['appInfo']['items'][0]['screen']['items'][0]['screen']['items'][0]['screen']['menuHeader'];
How can use index which is stored in variable to output data from json in php.
This should be similar to what you want:
$json = json_decode($finalAppData, true);
$link = "['appInfo']['items'][0]['screen']['items'][0]['screen']['items'][0]";
# Method #1
eval("echo \$json${link}['screen']['menuHeader'];");
# Method #2
$item = "\$json${link}";
eval("echo ${item}['screen']['menuHeader'];");
eval() takes a string of PHP code and interprets it. In this case, the nested keys are stored as a string in $link and then concatenated with a string that will be interpreted into the $json array resulting in a string of PHP code that will be sent to eval() to be interpreted.

Query and decode json form mysql database

I have this JSON encoded code in my mysql database:
{"Suggestion":{"Title":"Casinos","Text":"maybe it will be good if its there casinos "},"ID":6,"VoteNo":[],"Status":"Voting","Player":{"SteamID":"STEAM_0:1:36988062","Name":"Pepi"},"Approved":{"Name":"Nido Johnson","Is":true,"SteamID":"STEAM_0:0:47457253"},"VoteYes":{"1":"STEAM_0:0:56939043","2":"STEAM_0:0:55948188","3":"STEAM_0:1:25856984","4":"STEAM_0:1:40894071"}}
And i want to query and decode it to echo it at my website.
You have to use a php "json_decode()" function to decode a json encoded data.
Basically json_decode() function converts JSON data to a PHP array.
Syntax: json_decode( data, dataTypeBoolean, depth, options )
data : - The json data that you want to decode in PHP.
dataTypeBoolean(Optional) :- boolean that makes the function return a PHP Associative Array if set to "true", or return a PHP stdClass object if you omit this parameter or set it to "false". Both data types can be accessed like an array and use array based PHP loops for parsing.
depth :- Optional recursion limit. Use an integer as the value for this parameter.
options :- Optional JSON_BIGINT_AS_STRING parameter.
Now Comes to your Code
$json_string = '{"Suggestion":{"Title":"Casinos","Text":"maybe it will be good if its there casinos "},"ID":6,"VoteNo":[],"Status":"Voting","Player":{"SteamID":"STEAM_0:1:36988062","Name":"Pepi"},"Approved":{"Name":"Nido Johnson","Is":true,"SteamID":"STEAM_0:0:47457253"},"VoteYes":{"1":"STEAM_0:0:56939043","2":"STEAM_0:0:55948188","3":"STEAM_0:1:25856984","4":"STEAM_0:1:40894071"}}';
Assign a valid json data to a variable $json_string within single quot's ('') as
json string already have double quots.
// here i am decoding a json string by using a php 'json_decode' function, as mentioned above & passing a true parameter to get a PHP associative array otherwise it will bydefault return a PHP std class objecy array.
/ just can check here your encoded array data.
// echo '<pre>';
// print_r($json_decoded_data);
// loop to extract data from an array
foreach ($json_decoded_data as $key => $value) {
echo "$key <br/>";
foreach($value as $k=>$data)
{
echo "$k | $data <br/>";
}
}

PHP: Illegal string offset

I know there already are questions like this, but It didn't help me.
I get the follow error on my site:
Warning: Illegal string offset 'networkConnections' in
/var/www/bitmsg/templates/header.php on line 25 {
The line is
<?= $bmstatus["networkConnections"] ?> p2p nodes
if I print_r $bmstatus, then I get:
{
"numberOfBroadcastsProcessed": 2308,
"networkStatus": "connectedAndReceivingIncomingConnections",
"softwareName": "PyBitmessage",
"softwareVersion": "0.4.1",
"networkConnections": 52,
"numberOfMessagesProcessed": 22888,
"numberOfPubkeysProcessed": 8115
}
How to I fetch the information from this array?
I've tried both $bmstatus['networkConnections'] and $bmstatus->networkConnections
but both is returning that error?
$bmstatus contains a JSON string. You have to decode it first to be able to extract the required information out of it. For this purpose, you can use the built-in function json_decode() (with the second parameter set as TRUE to get an associative array, instead of an object):
$json = json_decode($bmstatus, true);
echo $json['networkConnections'];
It's a json string. You need to decode your json response using json_decode with second parameter true to get as an associative array.
$bmstatusArray = json_decode($bmstatus,true);
echo $bmstatusArray["networkConnections"];

Categories