how to fetch image from database in php? OR Store and Retrieve Image from MySQL Database using PHP.
how to fetch image from database in php?
Firstly, create a connection to the MySQL database. · After that, Write input fields to store images using Php.
store_retrieve_image_from_database/
├── dbConfig.php
├── index.php
├── upload.php
├── view.php
└── css/
└── style.css
Don’t Miss : How to fetch image from database in php and display in table?
Create Database Table
CREATE TABLE `images` ( `id` int(11) NOT NULL AUTO_INCREMENT, `image` longblob NOT NULL, `created` datetime NOT NULL DEFAULT current_timestamp(), PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Database Configuration (dbConfig.php)
<?php $dbHost = "localhost"; $dbUsername = "root"; $dbPassword = "root"; $dbName = "itsolutionstuck"; $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); if ($db->connect_error) { die("Connection failed: " . $db->connect_error); }
Image Upload Form
<form action="upload.php" method="post" enctype="multipart/form-data"> <label>Select Image File:</label> <input type="file" name="image"> <input type="submit" name="submit" value="Upload"> </form>
Store Image File in Database (upload.php)
<?php require_once 'dbConfig.php'; $status = $userMessage = ''; if(isset($_POST["submit"])){ $status = 'error'; if(!empty($_FILES["image"]["name"])) { $fileName = basename($_FILES["image"]["name"]); $fileType = pathinfo($fileName, PATHINFO_EXTENSION); $allowTypes = array('jpg','png','jpeg','gif'); if(in_array($fileType, $allowTypes)){ $image = $_FILES['image']['tmp_name']; $imgContent = addslashes(file_get_contents($image)); $insert = $db->query("INSERT into images (image, created) VALUES ('$imgContent', NOW())"); if($insert){ $status = 'success'; $userMessage = "File uploaded successfully."; }else{ $userMessage = "File upload failed, please try again."; } }else{ $userMessage = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.'; } }else{ $userMessage = 'Please select an image file to upload.'; } } echo $userMessage; ?>
Retrieve image from database (view.php)
<?php require_once 'dbConfig.php'; $result = $db->query("SELECT image FROM images ORDER BY id DESC"); ?> <?php if($result->num_rows > 0){ ?> <div class="gallery"> <?php while($row = $result->fetch_assoc()){ ?> <img src="data:image/jpg;charset=utf8;base64,<?php echo base64_encode($row['image']); ?>" /> <?php } ?> </div> <?php }else{ ?> <p class="status error">Image(s) not found...</p> <?php } ?>