how to fetch image from database in php

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.

how to fetch image from database in php
how to fetch image from database in php

├── 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` (
  `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)

$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">

Store Image File in Database (upload.php)

require_once 'dbConfig.php'; 

$status = $userMessage = ''; 
    $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())"); 
                $status = 'success'; 
                $userMessage = "File uploaded successfully."; 
                $userMessage = "File upload failed, please try again."; 
            $userMessage = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.'; 
        $userMessage = 'Please select an image file to upload.'; 
echo $userMessage; 

Retrieve image from database (view.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 } ?> 
<?php }else{ ?> 
    <p class="status error">Image(s) not found...</p> 
<?php } ?>

Leave a Reply

Your email address will not be published.