PHP MYSQL

STORE RETRIEVE IMAGES IN DATABASE 

img_name | varchar(255) UNIQUE img_data | longblob NOT NULL

DATABASE TABLE

01

<form method="post" action="UP.PHP"             enctype="multipart/form-data">    <input type="file" name="upload"                 accept=".png,.gif,.jpg,.webp">    <input type="submit" value="GO!"> </form>

HTML IMAGE UPLOAD FORM

02

CONNECT TO DATABASE $pdo = new PDO(   "mysql:host=HOST;dbname=NAME;   charset=utf8", USER, PASSWORD );

PHP STORE IMAGE (A)

03

PREPARE INSERT $stmt = $pdo->prepare("INSERT INTO `images` (`img_name`, `img_data`) VALUES (?,?)");

PHP STORE IMAGE (B)

04

SAVE UPLOADED FILE INTO TABLE $stmt->execute([   $_FILES["upload"]["name"],   file_get_contents($_FILES["upload"]   ["tmp_name"]) ]);

PHP STORE IMAGE (C)

05

CONNECT TO DATABASE $pdo = new PDO(   "mysql:host=HOST;dbname=NAME;   charset=utf8", USER, PASSWORD );

RETRIEVE IMAGE (A)

06

PREPARE SELECT $stmt = $pdo->prepare("SELECT `img_data` FROM `images` WHERE `img_name`=?");

RETRIEVE IMAGE (B)

07

EXECUTE & FETCH $stmt->execute(["IMAGE.JPG"]); $img = $stmt->fetch();

RETRIEVE IMAGE (C)

08

DIRECT OUTPUT IMAGE echo $img['img_data'];

OR EMBED INTO <IMG> TAG $img = "data:image/jpg;base64,". base64_encode($img['img_data']);   <img src="<?=$img?>"/>

DISPLAY IMAGE

09