テーブルを作成
$ CREATE TABLE test(image bytea);
bytea型はバイナリデータを保存。1Gまで可能
https://www.postgresql.jp/document/9.6/html/datatype-binary.html
画像データの登録
$dsn = "pgsql:dbname=testdb host=localhost port=5432";
$user = "user1";
$password = "password";
try {
$dbh = new PDO($dsn, $user, $password);
print('connection success<br>');
$stmt = $dbh->prepare("insert into test (image) values (:image)");
$fp = fopen("images.jpeg", "rb");
$stmt->bindParam(':image', $fp, PDO::PARAM_LOB);
$stmt->execute();
} catch(PDOException $e){
print("Error:".$e->getMessage());
die();
}
画像の表示
$dsn = "pgsql:dbname=testdb host=localhost port=5432";
$user = "user1";
$password = "password";
try {
$dbh = new PDO($dsn, $user, $password);
$stmt = $dbh->prepare("select image from test");
$stmt->execute();
$stmt->bindColumn("image", $image, PDO::PARAM_LOB);
$stmt->fetch();
header("Content-Type: image/jpeg");
fpassthru($image);
unset($db);
} catch(PDOException $e){
print("Error:".$e->getMessage());
die();
}
なるほど、DBに画像保存も可能なのね。
データサイズが気になるが、軽量な画像であれば良さそう