In this tutorial i will explain you that how we can upload our image to MySQL Database using PHP. In this tut i am also introduce you with BLOB column type in MySQL.

What is BLOB?

A blob is a collection of binary data stored as a single entity in a database management system. Blobs are typically images, audio or other multimedia objects, though sometimes binary executable code is stored as a blob. Wikipedia
In Simple words BLOB is used to store data to database in a binary format.
MySQL have four type of BLOB :

  • TINYBLOB
  • BLOB
  • MEDIUMBLOB
  • LONGBLOB

BLOB help us to solve these issue

  1. Store image to database give us better security.
  2. Eliminates messy directory and file structures.

But there are some disadvantages of BLOB like

  1. You are unable to access your file directly using ftp
  2. It will increase your database size.
  3. Migrating to a new database is made more difficult.

Now we create a simple form to upload and display image from database using php.
Database :

create database if not exists img

CREATE TABLE IF NOT EXISTS `dbimg` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `name` text NOT NULL,
  `src` blob NOT NULL,
  `type` text NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

Code Form :

<form action="" method="post" enctype="multipart/form-data">
	<div>
	   <label>Image:</label>
	   <input type="file" name="image" value="">
	</div>
	<div>
	   <input type="submit" value="Upload">
	</div>
</form>

simple form where we select file to upload.

Database Connection conn.php

// Connection
$con = mysql_connect("localhost", "root", "");
mysql_select_db("img", $con);

Handle form data and upload image to database

<?php
if(isset($_FILES['image']['name'])){
        // *** Add your validation code here *** //
        // Include Connection
	include_once('conn.php');

	// Get Image
	$name = $_FILES['image']['name'];
	$type = $_FILES['image']['type'];
	$get_content = file_get_contents($_FILES['image']['tmp_name']);
	$escape = mysql_real_escape_string($get_content);
	$sql = "INSERT INTO `img`.`dbimg` (`ID`, `name`, `src`, `type`) VALUES (NULL, '$name', '$escape', '$type');";
	if(mysql_query($sql)){
		echo 'Image inserted to database';
	}else{
		echo 'Error data inserting';
	}
}
?>

In above code we simply get uploaded image and insert it to database. You also add your validation in above code.

Now we display uploaded image:

<?php
// Connection
include_once('conn.php');
$sql = "SELECT * FROM  `dbimg`";
$qur = mysql_query($sql);
while($r = mysql_fetch_array($qur)){
	extract($r);
	echo '<img src="data:image/png;base64,'.base64_encode($src).'">';
}
?>

In above code we display our uploaded image on browser using base64 encoded picture.

A simple code but good to learn.

Posted in: php