Reputation:
Context, I am doing this PHP project that has function update a product data, the situation is the product has an amount of data, after the update, I pack all the data as a JSON object and store into MySQL DB. the reason of packing everything into one JSON object and store as one MySQL row is: in this project, the different product has different attributes, so I think this would be a quick solution for a temporary storing data.
Problem, when I fetch back certain JSON object from MySQL DB, I can not access JSON object, I used JSON decode, but it not works.
here is how I created JSON object
$product_INFO = (object)array(
"ean_number" => "$Static_eanNumber",
"product_name" => "$productName",
"product_brand" => "$Brand",
"product_weight_gr" => "$weight_GR",
"product_vatrate" => "$vat__Rate",
"product_supplier" => "$SUPPLIER",
"product_googleShoppingCategory" => "$GOOGLE_ShoppingCategory",
"LIGHTSPEED_INFO" => $LIGHTSPEED_product_info_array
);
and encode
$Data_in_JSON = json_encode($product_INFO);
query
$write_JSON_object = "INSERT INTO editing ( eannumber, json) VALUES ('$Static_eanNumber','$Data_in_JSON')";
in mysql database table, the column for JSON is Name: json Type: LongText Collation: utf8mb4_bin
when I fetch from the database, I use this query
$find = "SELECT json FROM editing WHERE eannumber = 10000007 ";
and
if (($found->num_rows) == 1) {
$mysqlJSON = mysqli_fetch_array($found)[0];
echo "<pre>";
print_r($mysqlJSON);
echo "</pre>";
}
This is the result I see on an HTML page
{"ean_number":"10000007",
"product_name":"somevalue",
"product_brand":"Leba",
"product_weight_gr":"65000",
"product_vatrate":"0.21",
"product_supplier":"LebaBenelux",
"product_googleShoppingCategory":"",
"LIGHTSPEED_INFO": [{"product_shop_id":68295980,"product_price":"2854.9533"..........
I tried to use JSON decode the MySQL fetch result but it not works, So I cannot access this result by their keys such as "ean_number",
print_r(json_decode($mysqlJSON)->ean_number);
I cannot tell where did I made mistake, I create a JSON object in the wrong way? something wrong with MySQL or how I fetch data.
Please help thanks!!!
Upvotes: 1
Views: 1352
Reputation: 2061
Your code is working for me but you can also change json_decode($mysqlJSON)->ean_number
to json_decode($mysqlJSON)
and then access the property you want:
$json = '{"ean_number":"10000007",
"product_name":"somSomething is wrongue",
"product_brand":"Leba",
"product_weight_gr":"65000",
"product_vatrate":"0.21",
"product_supplier":"LebaBenelux",
"product_googleShoppingCategory":""}';
$decoded = json_decode($json);
echo $decoded->ean_number;
Upvotes: 2