How to fetch image from database in php and display in table?

How to fetch image from database in php and display in table? – Store and Retrieve Image from MySQL Database using PHP Full Source code. Connect PHP with MySql connection Create a query return result show HTML Table.

how to fetch image from database in php and display in table?

├── connection.php
├── index.php
├── do_upload.php
├── view.php
└── css/
└── style.css

Step 1: Create Database Table

CREATE TABLE `members` (
  `image` longblob NOT NULL,
  `created_at` datetime NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Step 2: Database Configuration


$dbHost     = "localhost";  
$dbUsername = "itsolutionstuck";  
$dbPassword = "itsolutionstuck@898956";  
$dbName     = "itsolutionstuck";  
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);  
if ($db->connect_error) {  
    die("Connection failed: " . $db->connect_error);  

Step 3: Image Upload Form

<form action="do_upload.php" method="post" enctype="multipart/form-data">
    <label>Select Profile Img File:</label>
    <input type="file" name="image">
    <input type="submit" name="submit" value="Upload">

Step 4: Store Image File in Database


require_once 'connection.php'; 
$is_available = $displayNotify = ''; 
    $is_available = '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 members (image, created_at) VALUES ('$imgContent', NOW())"); 
                $is_available = 'success'; 
                $displayNotify = "File uploaded successfully."; 
                $displayNotify = "File upload failed, please try again."; 
            $displayNotify = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.'; 
        $displayNotify = 'Please select an image file to upload.'; 
echo $displayNotify; 

Step 5: Retrieve image from database


require_once 'connection.php'; 
$result = $db->query("SELECT image FROM members 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="is_available error">Image(s) not found...</p> 
<?php } ?>

Leave a Reply

Your email address will not be published. Required fields are marked *