The problem
The problem is that:
You are selecting all columns in the table: SELECT * FROM features WHERE id = 1;
You are creating an array: $json = $stmt->fetch();
Something like this:
Array
(
[persona_id] => 9
[persona_nom] => {"A":"1","B":"0","C":"1"}
[ciudad_id] => 12
)
You are trying to apply json_decode
to that array: $resultado = json_decode($json);
When that function should receive as parameter a string, not an array .
The result of that procedure is the following Warning:
PHP Warning: json_decode () expects parameter 1 to be string, array
given
and you get a value NULL
because the parameter could not be decoded because it was incorrect.
The solutions
1.
Since the course JSON, (I'm guessing because it's actually a VARCHAR
within which you're saving a string in the form of JSON), it's in a single column of that table, you can get it by accessing the data in that column specifically.
For example:
$json = $stmt->fetch(PDO::FETCH_ASSOC);
$resultado = json_decode($json["persona_nom"]);
print_r($resultado);
There you will have on screen:
{"A":"1","B":"0","C":"1"}
2.
Anyway, here the use of json_decode
is redundant, since, supposedly , there should be a valid json in the VARCHAR
column. In fact, if you do this:
print_r ($json["persona_nom"]);
The result is the same as if you were using json_decode
:
{"A":"1","B":"0","C":"1"}
And if that value should be received as a valid JSON elsewhere (an Ajax call, a REST server, etc), you could use the header before the print_r
would suffice.
3. The best solution
Nothing better than when they treat you like what you are. In that sense, MySQL allows you to use a data type JSON
, maybe it's the more appropriate, if you want to store JSON objects in your database.