Tropicalista
Tropicalista

Reputation: 3137

Retrieve a json field from mysql field with PDO

I have a database where I store some data, and one field is a json string.

I insert an json in this field:

        $stmt->bindParam(":settings", json_encode($widget->settings));

Then when I try to retrieve the record I get my row with the settings column as string. I need my data to be json, so I should decode this field before output my records. If i go with:

        $app->response->setBody(json_encode($data, JSON_NUMERIC_CHECK));

I get something like:

"name":"My Name","label":null,"row":null,"settings":"{\"site\":\"dfsdf\",\"action\":\"UrlInfo\"}"

with settings escaped. I should first decode settings and then encode again to output my results. How can I do to solve this?

UPDATE:

I retrieve my data using PDO, so I get an array:

        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

Before I save this I have:

"settings":{"site":"fff","action":"UrlInfo"}}

Upvotes: 0

Views: 2181

Answers (1)

Barmar
Barmar

Reputation: 781059

When you retrieve the data, you should use json_decode to reverse the encoding that you did when you inserted it.

foreach ($data as &$row) { // Use reference so we can modify in place
    $row['settings'] = json_decode($row['settings']);
}
$app->response->setBody(json_encode($data, JSON_NUMERIC_CHECK));

Upvotes: 2

Related Questions