Handling BLOB image Upload and Displaying BLOB image using php, html

If you dont want to upload image directly to your server or handling same database with different FTP Connections you can use concept of BLOB image , through which we directly upload image into our database.

Step1: Create a column in your database of type TINYBLOB/ BLOB/ MEDIUMBLOB/ LONGBLOB based on your image size requirement

ALTER TABLE table_name ADD image LONGBLOB, ADD image_type varchar(255);

Step2: Create HTML form from where we can upload our image

<form action='' id='form_id' method='POST' enctype="multipart/form-data">
    <input type="file" name="images" required>
</form>
<button type="submit" form="form_id">Submit</button>

Step3: Now we have to handle the image upload through php as

if(isset($_FILES["images"]["name"]) && $_FILES["images"]["name"] <> ''){ 
  $image = $_FILES['images']['tmp_name'];
  $image_data = file_get_contents($image);
  $image_type = $_FILES['images']['type'];    
}
$imageData = base64_encode($imageData); //encoding in base64 to avoid syntax errors in sql query


$query = "INSERT INTO table_name (image, image_type) VALUES ('$image_data', '$image_type')";
mysqli_query($db, $query);

Step4: Now saving Blob image to database is done, Now we have to show this image in our view page

$sql = "SELECT image,image_type FROM table_name WHERE id='1' ";
$result = $db->query($sql);
$row = $result->fetch_assoc();
$image = $row['image'];
$image_type = $row['image_type'];
//based on image type replace your code with this following
<img src="data:image/jpeg;base64,<?php echo $image; ?>">
<img src="data:image/png;base64,<?php echo $image; ?>">

By following these simple steps we can use Blob Images

Sign In or Register to comment.