Despite of recent implementation of JSON datatype to MySQL I can't find any word on it in the related PHP documentation.
My question is: will PHP automatically convert cells of JSON column to the actual values - arrays or literals - or will it provide just json-encoded strings. Like:
$sql_query = "SELECT JSON_ARRAY(1,2,3)";
$result = mysqli_query($sql_query);
$value = mysqli_fetch_row($result)[0];
// what is a $value? Array(1,2,3) or a string "[1,2,3]"
// do I have to use json_decode() to get an actual array here?
(Don't have MySQL 5.7 at hand right now, so can't check it myself.)
i think with serialize and unserialize you get whatever you want.
so just store all values using serialize and you can get that values with unserialize.
so just check serialize and unserialize.
Related
I new in PHP programming and I try to make simple API with simple PHP. Below my snippet code :
$con = mysqli_connect(HOST, USER, PASS, DB);
$sql_results = mysqli_query($con, "SELECT * FROM `table-images`");
$rows = array();
while($r = mysqli_fetch_assoc($sql_results)) {
$rows[] = $r;
}
echo'{"response":'.json_encode($rows).'}';
The code above have JSON output like below :
{"response":[{"id":"31","shirtImage":"Content\/Images\/Short Sleeve\/874be7b82812f76c944d71706c9651eb.gif"},{"id":"32","shirtImage":"Content\/Images\/Short Sleeve\/b-Cleaned.png"}]}
I want to know why value of field shirtImage have extra symbol \ . In my database the value is correct example Content/Images/Short Sleeve/b-Cleaned.png but when it encode to JSON the output have changed. How to fix this?
I find some keyword regarding my case, but it still does not work.
There is nothing to fix.
JSON is a format that encodes a data structure in a way that makes it storable and transportable. When the data is needed for processing you have to decode it from JSON.
You can use json_decode() in PHP or JSON.parse() in JavaScript to restore the original data and work with it.
Many other languages provide a function or library to work with JSON.
You should not generate JSON manually. The correct way to produce a JSON from your data is:
$response = ['response' => $rows];
echo json_encode($response);
Because the values stored in $rows are arrays (and because it is easier to work with arrays in PHP than with bare objects) when you decode the JSON in PHP it's recommended to pass true as the second argument to json_decode(). This way it uses arrays in the restored data structure.
Otherwise it produces instances of stdClass which are bare PHP objects. The arrays are more versatile.
json_encode() escapes forward slash. Try using:
echo'{"response":'.json_encode($rows, JSON_UNESCAPED_SLASHES).'}';
Its due to escaping / with `\` and it will be removed when you decode your json back.
Try to decode it back.
$d = json_decode('{"response":[{"id":"31","shirtImage":"Content/Images/Short Sleeve/874be7b82812f76c944d71706c9651eb.gif"},{"id":"32","shirtImage":"Content/Images/Short Sleeve/b-Cleaned.png"}]}');
print_r($d);die; // This will give you the original data with out `\`
I am trying to extract some part of a JSON formatted string in CakePHP using the Hash::extract method .
Here is the JSON string:
[[{"name":"Atkins Global","y":{"count":96,"type":"1"}},
{"name":"HFT","y":{"count":444,"type":"1"}},
{"name":"Catalyst","y":{"count":8,"type":"1"}},
{"name":"BGL","y":{"count":2,"type":"1"}}]]
Here is what I used in CakePHP to retrieve the above JSON:
debug(json_encode(Hash::extract($data['type'], '{s}')));
$data['type'] holds the data above.
Is there a way I can grab the type values only? Not sure how I can do this in CakePHP. Would appreciate if anyone can help.
From an answer by Roberto Atkinson, you have to do json_decode() first to convert a JSON string to a PHP array, instead of encoding an array to JSON. Reference: json_decode()
In your case, try:
//from JSON string to PHP array; force returned objects to be converted into associative arrays
$data['type'] = json_decode($data['type'], true);
//now you can extract type values from data
$output = Hash::extract($data['type'], '{s}'));
In addition, according to CakePHP official API documentation: Hash::extract(), the first parameter should be an array.
Parameters (array|ArrayAccess $data The data to extract from., string $path The path to extract.)
I'm not sure if I'm allowed to ask these types of questions. Anyway, I have this array value $custom_fields['user_gender'][0] that outputs this:
a:2:{i:0;s:7:"Male";i:1;s:7:"Female";}
I'm not sure how to convert this into an array or string.
The example data looks like it is serialized PHP. Serializing is a way an array, string etc. can be "represented" as a textual string and can later be converted back to the original data format, using a unserialize operation. A serialized string can be stored as text in a database and can be unserialized at any point.
You can unserialize it with:
$array = unserialize($custom_fields['user_gender'][0]);
This should return an array. If you var_dump on $array, you can be sure it's an array.
I have this string stored in a database column:
O:8:"stdClass":2:{s:4:"type";s:5:"Point";s:11:"coordinates";a:2:{i:0;d:-23.5663719;i:1;d:-46.65284157;}}
And I just want the "coordinates" in the middle:
-23.5663719,-46.65284157
There is a easy way to parse it in PHP to get this value?
I tried json_decode but it didn't work.
Thanks.
It's not json encoded, but serialized using serialize().
So what you have to do is:
$o = unserialize($str); // where $str is a string fetched from DB
var_dump($o->coordinates);
References:
http://www.php.net/manual/en/function.serialize.php
http://www.php.net/manual/en/function.unserialize.php
I have my data stored in a JSON string like these...
a:1:{s:15:"s2member_level1";s:1:"1";}
How can i read this values in mysql?
I need to know if the value "s2member_level1" is 1.
Thanks!!!
That's not JSON but a string resulted from calling serialize() in PHP. You cannot parse it easily in MySQL. If you can use PHP, use the unserialize function:
$obj = unserialize($data_from_mysql);
if ($obj['s2member_level1'] == 1) {
// more code here
}
You can convert data to JSON in PHP using the json_encode function. In a similar way, you construct an object from a JSON string using json_decode.
#Lekensteyn is correct, but you could do a like statement, although its performance would most likely be very poor. My true answer is to change how you store this information to take advantages of best performing queries.
select * from table
where column like '%s:15:"s2member_level1";s:1:"1";%';
#Lekensteyn is right about the type of this particular String, but for others, PHP has json_decode which you can use to convert a JSON object to a PHP object. It would be considerably more difficult to read such an object using MySQL only.
This is no json, but serialized data. It was probably serialized with the 'serialize' function of PHP. Try:
print_r(unserialize('a:1:{s:15:"s2member_level1";s:1:"1";}'));
... to unserialize it.