How to store a Json data in one field? - php

I know this question has been asked a lot and I have researched, trust me.
I have a Json file with multi variables in it. I want to take that Json file and store it in a single BLOB field on MySql Database.
I did json_decode() but when I try to store it, PHP gives me an error because json_decode() returns a php array but bindParam wants a string varaible.
I tried implode(",", json_decode($data,true)) but it didn't work.
Can you help me please...
My JSON file looks like this;
[
{ "xyz": "abc",
"izd": 1
},
{ "xyz": "abc",
"izd": 1
},
{ "xyz": "abc",
"izd": 1
}]
My PHP code is like this;
$json = $_POST["jsonfile"];
$jsondata = json_decode($json,true);
$implodedjsondata = implode(",",$jsondata); // In here, php gets error in impode ( Error : Notice: Array to string conversion)
$Query = $conn->prepare("INSERT INTO table1(somedata) VALUES(:data)");
$Query->bindParam(':data',$implodedjsondata); // In case of not using implode, this line gets error( Error : Notice: Array to string conversion)
$Query->execute();
Thanks...

its already a json? don't do anything with it, insert it as-is. and use bindValue, bindParam is an optimization thing when you have a lot of data you need to change fast when loop-executing a statement..
$json = $_POST["jsonfile"];
$Query = $conn->prepare("INSERT INTO table1(somedata) VALUES(:data)");
$Query->bindValue(':data',$json); // In case of not using implode, this line gets error( Error : Notice: Array to string conversion)
$Query->execute();

Related

Read a JSON data value with mixed number and letter in key in PHP

I am stuck with this issue. I am trying to read data from openweathermap.org weather data API. One of the values, rainfall amount, is keyed with a digit and letter in the key. And PHP is throwing errors at me if I try to read it. Here is the code I'm trying to use.
$rainAmount = $data->hourly[$hour]->rain->1h;
and here is the JSON file (a portion of it anyways).
"rain": {
"1h": 1.78
}
This is data provided by the API so I can't just change the key that's used. Here is the PHP error
PHP Parse error: syntax error, unexpected integer "1", expecting identifier or variable or "{" or "$" in /home/
It's pretty obvious it is the digit in the key that is the issue. But how else do I read the value?
Thanks in advance.
Did you try:
$string = '{
"rain": {
"1h": 1.78
},
}';
$arr_weather = json_decode($string, true);
print $arr_weather['rain']['1h'];
The second parameter from json_decode(,, true is a bool to decode the data as an associative array. Please read more here about json_decode:
https://www.php.net/manual/en/function.json-decode.php
If you still want to work with your response as an object you can use the curly braces like this:
$string = '{
"rain": {
"1h": 1.78
},
}';
$weatherObject = json_decode($string);
print $weatherObject->rain->{'1h'};
But in this case, you have to know that if your key is a number only, it will not work, like $weatherObject->rain->{'12'} - So I recommend using the data as an array, like in the first example.

At a loss with JSON, PHP, AS3: Cannot trace correct value

I have used JSON objects before and they work perfectly but the JSON objects that I made before have been from a result of fetched MySQL entries. Now, I am trying to make my own JSON object through an array in PHP and it shows correctly in the database but I cannot access any of the values like before.
$chatArray = array(
array(
'chatusername' => 'Troy',
'chatuserid' => '123',
'chatmessage' => 'Hello World'
),
array(
'chatusername' => 'Nick',
'chatuserid' => '124',
'chatmessage' => 'Testing'
));
$inputArray = json_encode($chatArray);
That is what I input into my database and like I said it works good. Then I call for it in a separate .php and get this
{"chat":"[{\"chatuserid\": \"123\", \"chatmessage\": \"Hello World\", \"chatusername\": \"Troy\"}, {\"chatuserid\": \"124\", \"chatmessage\": \"Testing\", \"chatusername\": \"Nick\"}]"}
It throws the "chat" out front which is the column name in my database which I am not sure why.
When I trace it I can only seem to trace it by
var messageArray:Object = JSON.parse(event.target.data);
trace(messageArray.chat);
Any time I try to reference say messageArray.chat.chatusername it returns an error.
I'm sorry I know it is probably a simple solution but I have been searching and working at it for a few hours now.
Any help is much appreciated! Thank you!
From the PHP code that generates your JSON output:
$stmt = $conn->prepare("SELECT chat FROM markerinfo WHERE markerid='$chatid'");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($result);
Keep in mind that the chat column in your database contains a JSON-string.
This code is not decoding the JSON-string in your database, so $result will be an array containing a JSON-string as well:
$result = [
'chat' => '[{"chatusername":"Troy","chatuserid":"123","chatmessage":"Hello World"},{"chatusername":"Nick","chatuserid":"124","chatmessage":"Testing"}]'
];
By passing that array through json_encode(), you're double-encoding your JSON-string.
For your purposes, you can probably get away with:
echo $result['chat'];
But, if you want the chat column name to be included in your output, you will have to decode the stored JSON first:
$result['chat'] = json_decode($result['chat']);
echo json_encode($result);
Probably this is related to the php side when it encodes your array, it will escape it with slashes, and this confuses the JSON parsing in your JS side. Try to add the JSON_UNESCAPED_SLASHES option to your json_encode function like this:
$inputArray = json_encode($chatArray, JSON_UNESCAPED_SLASHES);
Check the json_encode function documentation for more details:
http://php.net/manual/en/function.json-encode.php

Postgresql query result PHP encode converted array to string

I have an SQL query that converts result to json.
SELECT 'FeatureCollection' As type, array_to_json(array_agg(f)) As features FROM (
SELECT 'Feature' As type,
ST_AsGeoJSON(geom)::json As geometry,
row_to_json((name, category)) As properties
FROM my_geometry_table
) As f ;
I am using this query in PHP script.
$result = pg_query($connection, $queryString);
$resultArray = pg_fetch_all($result);
echo json_encode($resultArray[0]);
My php result is like this: (array is double-quote )
{
type: "FeatureCollection",
features: "[]"
}
But it should be like this:
{
type: "FeatureCollection",
features: []
}
It's important to remember that JSON is a way of representing data inside a string. PHP does not know that something is JSON, only that it's a string.
You need to first decode the result from Postgres (which is a JSON string) so that you have a PHP array. Then you can encode that PHP array back to JSON:
$result = pg_query($connection, $queryString);
$resultArray = pg_fetch_all($result);
// $resultArray[0]['features'] is a string of JSON data from the DB
// For example, let's say it's '[1,2,3]'
// To you, this is obviously JSON: it looks like it,
// and you know you asked for that column to be JSON in the SQL.
// But PHP has no idea; it just sees a 7-character long string;
// so we need to tell it to decode that string:
$decoded_features_array = json_decode($resultArray[0]['features']);
// $decoded_features_array is now a PHP array containing 1, 2, and 3
// Obviously, you can just write that value straight back into the result
$resultArray[0]['features'] = json_decode($resultArray[0]['features']);
// Now the 'features' field of the result is an actual array,
// not a string, so we can do with it whatever we'd do with any other array
// That includes encoding it to send somewhere else - in this case, as JSON:
$json_result = json_encode($resultArray[0]);
// $json_result is now a string with all the fields
// and our PHP array gets encoded as a JSON array as we wanted:
// e.g. '{"type": "FeatureCollection", "features": [1,2,3]}'

How to get values from a PHP file querying MongoDB in jQuery's getJSON()?

I am learning MongoDB and hoped that because data stored in MongoDB databases was in a format very similar to JSON I would be able to query MongoDB directly from jQuery's getJSON() method.
I am learning however that it seems you need MongoDB and a driver to access the database from an application. So I am going with the PHP driver for the time being.
I am trying to return the value of the content field:
MongoDB Document
{
"_id": ObjectId("34576347347"),
"content": "here is some content",
"field2": {
"subfield1": {
"0": "sf1v0",
"1": "sf1v1",
"2": "sf1v2"
},
"subfield2": "value 2"
},
"field2": "value 3"
}
PHP
<?php
$dbhost = 'username:password#127.x.xx.x:27017/';
$dbname = 'dbname';
$m = new MongoClient("mongodb://$dbhost");
$db = $m->$dbname;
$collection = $db->myCollection;
$query = $collection->find(array("field2.subfield2" => "value 2"));
header("Content-type: application/json");
echo json_encode($query);
?>
jQuery
$.getJSON("http://path/to/mongo.php", {cid: href, format: 'json'}, function(results){
$("#my_div").html(results[0].content);
}
I think I need to 'get' a few things:
What is being returned from the PHP query:
$query = $collection->find(array("field2.subfield2" => "value 2"));
I think the MongoDB terminology it that it is returning the cursor, but is that a PHP array, or JSON data or something else?
What is the correct 'call' to make in the getJSON() code to return the required data?
At the moment Firebug is showing me:
TypeError: results[0] is undefined
Update
I changed getJSON() code to:
$("#my_div").html(results.content);
And now I don't get an error, but the following from Firebug:
Response tab shows: {}
JSON tab shows: There are no properties to show for this object.
You want to convert the cursor returned from the find() function to something json_encode can actually use like so:
$cursor = $collection->find(array("field2.subfield2" => "value 2"));
echo json_encode(iterator_to_array($cursor, false));
This is because the query is not run until you iterate the cursor. Iterator_to_array basically will exhaust the cursor, get all documents, and put them into an array for json_encode.
Edit
Specifying false as the second $use_keys argument to iterator_to_array() will ensure that the results are indexed numerically (instead of by the _id field of each document).

MYSQL SELECT and JSON_ENCODE

I need to select a key from a json_encodED array from mysql..
SELECT * FROM json_field_table WHERE {var from JSON encoded array} = {expected value}
or something..
How I can do this?
PS.: Poor English, I know..
You'd have to use substring matching. MySQL doesn't have anything to deal with JSON data and treats it like it does any other piece of random text.
SELECT ... WHERE the_json_field LIKE '%"var":"value"%';
Well, Gabriel, despite the nature of your question. I am supposing, your problem might be, you need to read a JSON value and based on that values, you need to retrieve the record set from the table. If this is the case, here is your solution.
// A sample json string
$json = '{ "field1": "value1", "field2": "value2" }';
// Here we will convert the json string into readable assocative array
$json_array = json_decode($json,true);
//Next we will use it on a query
$query = "SELECT * json_field_table WHERE `".$json_array['field1']."` = 'Some Value' ";
//Execute the query
$result = mysql_query($query);
with numbers (integers) you can filter out values, with alphanumeric strings is more complicated as the value stored is "jsonencoded"
check my answer to 17955206

Categories