I have written a query that fetches a document record, within this record there is a field called Attachment
, that stores the file location and properties as an array.
The query I have used to do this is:
$result=DB::Query("select * FROM dbo.Toolkit_ComplianceItems WHERE ToolkitItemPk= 114");
while($data = $result->fetchAssoc())
{
$array = $data["Attachment"];
echo $array;
}
And the echo outputs the array as the following:
[{
"name": "files\/Cairnhill Emergency Plan v.6.0 Sep 2022_dy8yokem.pdf",
"usrName": "Cairnhill Emergency Plan v.6.0 Sep 2022.pdf",
"size": 1020697,
"type": "application\/pdf",
"searchStr": "Cairnhill Emergency Plan v.6.0 Sep 2022.pdf,!:sStrEnd"
}]
so, I know both var_dump and echo return what I am expecting.
I am then trying to retrieve the exact field for say, the file name, which is recorded under "name" in this array, I am doing this by using:
echo "name: ".$array[0]["name"];
But for reasons I do not understand, I am getting the following error message:
Fatal error: Uncaught TypeError: Cannot access offset of type string on string
As far as I know, I am using the correct [array][0][name] structure, but can someone please point out what I have done wrong?
(PS I am aware that this query is open to SQL Injection, and I will correct that, after I have it working.)
CodePudding user response:
It appears that the data is stored as a JSON string within your database.
To get data from within a JSON string, you first need to decode it into a PHP object / array variable:
$data = json_decode($array, true);
echo "name: ".$data[0]["name"];
Demo: https://3v4l.org/7i1ZR
Note that I've used the option to decode the JSON into an associative array rather than an object, so you can use your existing code to read from it. Reference: https://www.php.net/manual/en/function.json-decode.php
See also: How to extract and access data from JSON with PHP?