[How to] Store and Display images from MySQL using PHP

Now everything is database driven and people are willing to involve the db technology everywhere. So, lets see what we can do to throw a image on the screen not directly from the directory, where it is stored as it is. But, we will see how we can store the image in DB and display images from db.

As we are going to do it, I want to tell you what are the procedures involved in it.

First, we will read the images in the binary mode(Binary mode because it can represent anything) using a PHP script, and all the binary code will be stored in the database as is.

Next, we will give the name or number to those data for the identification.

And at last, we will create a script which will access the db, read the data into it, and display image.

Sounds simple isn’t it? Here create a table named imagedb

Now lets create a page called ” store.php ” because it the page we will use to read the images, and store it in DB.

The code we will add to it are

Save the file, and now create a new file called “images.php” and add this code below. this is the page which will fetch us image from the DB.

$data = $sth->fetchAll();
echo $data;

Now type the url http://localhost/path/to/image.php?id=id_u_used , tadaaa, you can see the image.

if you want to put your images somewhere, just use

<img src=”image.php?id=image_id” />