I am trying to store image into postgresql bytea field.
$data=file_get_contents("filename.jpg");
pg_escape_bytea($data);
Then I am inserting this into database. After that when I select the image from the database it is showing Resource_id #. If I use pg_unescape_bytea()
on the selected field then it is showing null value.
How can I store and retreive data from postgresql using yii?
With PDO you shouldn't use the pg_*
functions, as these belongs to a different extension.
If you really want to store the image in bytea
, you should use the prepare/bind mechanism (or its Yii-DAO equivalent) to store image contents, and you should be aware that in (postgres) PDO the type bytea
is returned as a stream, so you can read it with functions like fread()
or stream_get_contents()
.
The way I do:
use yii\db\Expression;
$upload = UploadedFile::getInstance($model, 'upload');
$data = pg_escape_bytea(file_get_contents($upload->tempName));
$model->myfield = new Expression("'{$data}'");
To retrieve:
$data = stream_get_contents($model->myfield);