MySQLとPHPとPDOを使い、データベースに画像を格納、挿入して、表示させるものを作っていきたいと思います。10月1日記事
目次
CREATE TABLE images ( id int NOT NULL AUTO_INCREMENT, ext varchar(5), contents blob, PRIMARY KEY (id) );
※画像を同じ場所のフォルダに置いてテストしています。またconfig.phpについては、phpのconfigファイルをご参考ください。また、config.phpファイルの方も最後の?>は記入しなくても結構です。
<?php require ('config.php'); // 画像と拡張子を取得 $img_path = './hoge.jpg'; $img = file_get_contents($img_path); $ext = pathinfo($img_path, PATHINFO_EXTENSION); // データベースに保存 $dsn = 'mysql:dbname='.DB_NAME.';host='.DB_HOST.';port='.DB_PORT.''; $user = DB_USER; $password = DB_PASSWORD; $dbh = new PDO($dsn, $user, $password); $stmt = $dbh->prepare('INSERT INTO images VALUES(0, :ext, :img)'); $stmt->bindParam(':ext', $ext); $stmt->bindParam(':img', $img); $stmt->execute(); ?>
<?php header('Content-type: image/jpeg'); require ('./config.php'); $dsn = 'mysql:dbname='.DB_NAME.';host='.DB_HOST.';port='.DB_PORT.''; $user = DB_USER; $password = DB_PASSWORD; $id = "1"; try{ $dbh = new PDO($dsn, $user, $password); }catch (PDOException $e){ print('Connection failed:'.$e->getMessage()); die(); } $stmt = $dbh->prepare("SELECT * FROM images WHERE id = :id"); $stmt->bindParam(':id',$id,PDO::PARAM_INT); $stmt->execute(); $result = $stmt->fetch(); echo $result["contents"];
※最後の?>がないところがポイントです。書いてもいいですが、書かないことが推奨されています。
https://teratail.com/questions/14496を参考にしました。