how to fetch images from database in php

here we learn to dynamically Store and Retrieve Image from MySQL Database using PHP jquery Ajax Example with Demo.

How to Retrieve Image In PHP?

index.php

<!DOCTYPE html>
<html>
<head>
<title>get PNG, JPG or JPEG Image retrieve</title>
</head>

<body>
<form name="form1" action="" method="post" enctype="multipart/form-data">
<table>
<tr>
<td><input type="submit" name="store_img" value="display"></td>
</tr>
</table>
</form>
<?php
$con = mysqli_connect('localhost','root','','gandhi_shops') or die('Unable To connect');


if(isset($_POST["store_img"]))
{
   $res=mysqli_query($con,"select * from products");
   echo "<table>";
   echo "<tr>";
   
   while($product=mysqli_fetch_array($res))
   {
   echo "<td>"; 
   echo '<img src="data:image/jpeg;base64,'.base64_encode($product['image'] ).'" height="150" width="150"/>';
   echo "<br>";
   ?><a href="remove.php?id=<?php echo $product["id"]; ?>">Delete</a> <?php
   echo "</td>";
   } 
   echo "</tr>";
   
   echo "</table>";
  }
?>
</body>
</html>

Also Read: Ajax Image Upload without Refreshing Page using Jquery

how insert and retrieve images to and from database using php?

Create Database Table

CREATE TABLE `products`

CREATE TABLE `products` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `image` longblob NOT NULL,
 `uploaded` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration

database_connection.php

<?php   
$dbHost     = "localhost";  
$dbUsername = "root";  
$dbPassword = "DSFdsf7d5f4d#$$dkfjd98956";  
$dbName     = "gandhi_shop";  
   
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);  
    
if ($db->connect_error) {  
    die("Connection failed: " . $db->connect_error);  
}

Also Read: insert delete image from folder in php with jQuery

Image Upload Form

html code

<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 'database_connection.php'; 
 
$status = $saveImagesMessage = ''; 
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 products (image, uploaded) VALUES ('$imgContent', NOW())"); 
             
            if($insert){ 
                $status = 'success'; 
                $saveImagesMessage = "Profile uploaded successfully."; 
            }else{ 
                $saveImagesMessage = "Profile upload failed, please try again."; 
            }  
        }else{ 
            $saveImagesMessage = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.'; 
        } 
    }else{ 
        $saveImagesMessage = 'Please select an image file to upload.'; 
    } 
} 
 
// Display status message 
echo $saveImagesMessage; 
?>

Also Read: Capture Webcam Image with PHP and jQuery

Also Read This ๐Ÿ‘‰   php add array to array - Append One Array To Another In PHP

Retrieve image from database

view.php

<?php  
require_once 'database_connection.php'; 

$all_products = $db->query("SELECT image FROM products ORDER BY uploaded DESC"); 
?>

<?php if($all_products->num_rows > 0){ ?> 
    <div class="gallery"> 
        <?php while($product = $all_products->fetch_assoc()){ ?> 
            <img src="data:image/jpg;charset=utf8;base64,<?php echo base64_encode($product['image']); ?>" /> 
        <?php } ?> 
    </div> 
<?php }else{ ?> 
    <p class="status error">Your Image(s) not found...</p> 
<?php } ?>