Learn PHP
Site Map
Php Functions
C++ - Starting Out
Web Design Tools
Photoshop Tutorials
Droid Phones
Building Websites
ArrowTech Blog
Web Servers
Making Money
Favorite Links
Privacy Policy
Category: php

How to get images out of mysql database with php and use them on my webpages

Retrieving Images From Mysql Database With php

Author: D.Shaun Morgan

  • PHP Version - PHP 5x
  • Mysql Version - 5
Tutorial Outline:

Download Test Scripts

  1. Creating a Test Mysql Database
  2. Php Script to Load Images in Mysql Database
  3. Method 1 - Php Script to fetch images from mysql database
  4. Method 2 - Php Script to fetch images from mysql database
  5. Example of calling php script with img HTML tag
  6. Explanation of Image Script
  1. Create folder called "test"
  2. Create files "test01.php, test02.php, test03.php, test04.php & db_connection.php"
  3. Copy/Save test image into "test folder" a folder called "test"
See Also:
  1. How to store images in MySql database

This tutorial expands on another database/image how-to How to Store Images in Mysql Database. In the Images In tutorial I showed you the basic steps to opening a file (your image file) and reading it into a variable ($img), converting that file using php's base64_encode() function, and sticking that file into a Mysql database. Now, you will learn how to bring those images back out of a Mysql database, and render them to a web browser.

This Tutorial will cover two different ways to fetch and render images from a MySQL database

Create a mysql database with a table matching (Database Example)

CREATE TABLE `pictures` ( `id` int(8) NOT NULL AUTO_INCREMENT, `pic` blob NOT NULL, `ext` varchar(4) NOT NULL, `gender` varchar(7) NOT NULL, PRIMARY KEY (`id`), KEY `id` (`id`) )

Database Description

  1. Database name is "test_imgs"
  2. Table name is pictures
  3. "id" is primary, key, not null, and auto_increment
  4. "pic" blob not null
  5. "ext" is varchar(4) not null
  6. "gender" is varchar(7) not null
  7. I will assume English mysql defaults for everything else.
  8. Practice script "test.php"

Database Example

id pic ext gender
1 retergfghfghterhgcfnt
jpg female

Now - Create a directory on your web server and call it "test"

Create a file named "test01.php" in the"test" directory, and copy the Uploading Images Script to it.

The Uploading Images Script, originated in another php tutorial about Putting Images in a Mysql Database.

Uploading Images Script - test01.php

Copy test image intotest folder.

Test Image

testpic.jpg test image 1

Create a file named "test02.php", copy the contents of the PHP Image Rendering Script to it, then save it to the test directory.

PHP Image Rendering Script

Method 1# - rendering database images with php and MySQL.

This method determines what type of image is retrieved from the database, and uses the php header() function to setup and render the images.

PHP Image Render Script - Method 1 - test02.php

Method 2# - Image Rendering

Create a file named "test03.php" copy the Second Method Script to it. (See below)

Second Method Script - test03.php

Create a file named " db_connection.php" copy the Database Connection Parameters below

Database Connection Parameters

Create a file named "test04.php" copy the HTML for test_04.php (See below)

HTML for test_04.php

Explanation of Scripts

After building the database, and uploading all the example files and images to your server:

1. Navigate and execute test01.php script

testpic.jpg will be uploaded to your MySql server with an id of "1".

Picture Table

2. Click Method 1 to view your image. This particular script sends headers and render the jpg image via php script.

3. Next - Hit the Browser Back Button and click Method 2.

Notice that on the test04.php page, I inserted src="test_03.php" in the img tag. Doing this causes the test_03.php script to execute; the img tag sets up the headerfor theweb-browser.

Author: D.Shaun Morgan

how to make browser go back to last page with using php

How To Make Browser Go Back To Last Page With Php8/12/2014After submitting an HTML form or clicking a link encoded with variables and information, it is often desirable to the programmer that the user's browser be automatically redirected - to go back to the previous p

binary search user functions

Binary Search User FunctionThe code in the example is for finding a given value in a sorted array.If the value is not found the function will return the position of the location where it the value should be.

php conditional statments if else switch

Conditional Statements If Else & Switch CaseIf ElseIf else is the bread an butter of programming - so-to-speak. if-else and Case Switch are known as conditional operators; they create conditions or criteria that a block of

textarea code overflow

Textarea Code Overflows and Runs Out Onto PageMy Decision to Use Textarea TagWhile working on a script for to edit content, I ran into few problems. First - because mrarrowhead is a website about building websites using php, I have had to battle with the best way to disp

creating image watermarks

Creating PHP Watermarks$my_image = imagecreatefromjpeg('photo.jpeg');$watermark = imagecreatetruecolor(100, 70);imagefilledrectangle($watermark, 0,0, 99, 99, 0x0000FF);imagefilledrectangle($watermark, 9

odd number php script

Testing for Odd/Even Numbers - PHPExample - Banner Rotation PHP Script Odd/Even NumbersSimple Php Tutorial Creating Odd / Even Testing% modulus operator.$_SESSION['x'] % 2;

using php cookies variables

Using Cookie Variables in PHPSetting cookies in php is pretty straight forward. There is a php functionsetcookie();This function must be called before any anything else on the page or it will fail. There are two options to address

how to unzip files on your free hosting account

Uzipping Files on Your Web ServerIf you are using a free hosting account with godaddy.com and many of the other Free hosts out there, you may have found that they don't offer you a lot of features. One feature that I could not find on Godaddy.com free hosting accounts was a utility tha

passing data from one form to another form using php

Passing data from one form to another formTo pass php data from a form and then catch that data into another form one way to accomplish this task is to intermingle your php code into your HTML to dynamically capture variable values. This particular method is

Just In Time Compiling

JIT - Just in Time Compilers JIT refers to a special software that is found in web-browsers, and scripting engines such PHP's Zend. (My understanding of ZEND is that it produces byte-code and functions similar to other JIT compilers). For this discussion, without tryin

Storing image locations mysql

Store Image URL in DatabaseRetrieve Image with PHP Script Saving URL Text in Database Saving image filesystem paths, of an image file in

how to turn variable value into variable name

Variable Variables in PHPEvery so often when you are writing a php file, we all run into a situation where we would like for the name of the string that is inside of your php variable to be converted into the actual name of another variable.


Explanation of PHP Basic Syntax --New to PHPPhp is a language that is very much like writing c. The best feature of PHP versus c is that it is designed primarily to be used on WebPages -- allowing the author to intermingle their php code and the HTML on t

how to use dreamweaver

Dreamweaver - WISIWIGDreamweaver is a tool that arguably could be called the industry standard for web design.Dreamweaver, is an Adobe product that originally belonged to Macromedia. They sold out to Adobe a few years ago. I have been using Adobe/Macromedia Dreamweaver for


Filezilla Ftp Client, FTP SERVER vs WsftpBy D.Shaun MorganWhile I was writing this article, about halfway through, I realized that it would be unfair to tell my readers about Filezilla without also mentioning another very good FTP client called WSftp. So, I backtracked and

notepad plus

Notepad++Download Notepad Plus Plus Notepad plus plus is an open source, free text editor. It is an ideal choice for many programming and scripting languages. Example - How to write c++ w

how to open create write files using php

Php file functions, Opening a file in php, reading a file in php, writing a file in phpIn this tutorial we will look at the most commonly used file functions used in php. The examples below should be pretty familiar to the seasoned php scripter, but they are useful nonethel

stop form spam captcha

PHP -- How to Protect My Email Form / Contact Form Against Spam BotsAuthor D.Shaun MorganRandom Name Fields to Stop SpambotRandom Name Fi

retreive images mysql using php

How to get images out of mysql database with php and use them on my webpagesRetrieving Images From Mysql Database With phpAuthor D.Shaun MorganPHP Version - PHP 5xMysql Version - 5Tu

store images mysql using php

Storing Images in Mysql DatabaseTutorial OutlineCreating a Test Mysql DatabaseExample php Database FunctionExplanation of Database Function

php example post array

Visual example of how PHP handles the super-global array variable "$_POST"Author D.Shaun MorganVersions and Skill LevelPHP Version - PHP 5xReader skill level - BeginnerXHTML 1.0 Transition

php arrays

Passing PHP ArraysHow to pass php variable arrays between pages.Author Author D.Shaun Morgan

how to write php functions

Explanation of a Basic PHP FunctionWhat is a PHP function?In PHP a function represents a block of instructions that perform a task. A PHP Function allows the user to re-use blocks of script without having to rewrite all the

how to write html form using php

When learning PHP to build a website, one of the very first things that any newcomer, or beginner needs to learn is how to use HTML or XHTML ( will mean the same for this tutorial.) forms to collect information from users. Those data are usually email addresses, names, birthdays, and

register globals long arrays

Security, php.ini, register_globals and register_long_arraysAuthor D.Shaun MorganVersions and Skill LevelPHP Version - PHP 5xReader skill level - ALLTutorial Outline

how to install php 5

How to Install PHP 5.x.x.x on WindowsThis is beginner's how-to manual explaining how to quickly setup a PHP 5 installation on a Windows PC. You must have an Apache webserver installed and working on your personal computer.This tutorial was written primarily for configuri

php passing variables

Pass Variables from One Page to Another -- PHPTutorial Outline Passing PHP variables with


Leave a Comment




Enter The Captcha:

Author: Ravi Lohia | Website URL: |
On using the function imagecreatefromstring() function it shows an error, "Call to undefined function imagecreatefromstring()".What should I do now.


Check your syntax , and make sure that your php installation supports this image function. Typically if you are wanting to create images in php you will need to have what is call the GD libray installed and available.

Look at the following link:

Author: Cegonsoft | Website URL: http://www.cegonsoft.co.in |
Hi all,

I have stored images in database.. But while retrieving images, I couldn't get full picture..

Am just getting half of the image only.. This is my code.. Can anyone give me suggestions..

#connect to mysql server
$link = mysql_connect localhost , root ,

if $link {
die Not connected : . mysql_error

$db_selected = mysql_select_db images , $link

if $db_selected {
die Database error : . mysql_error

$sql = SELECT FROM testimage where sno=4
#the result of the query
$result = mysql_query $sql or die Invalid query: . mysql_error

while $image = mysql_fetch_assoc $result {
$a=$image[ image ]
$b=$image[ name ]
header Content-type: $b
echo $a

Author: pradeep | Website URL: |
i would like to know the inserting image into mysql database using php .i hope i will get the info in detail.
Author: ankit | Website URL: |
I have tried the above code and getting following error while retrieving images

Warning: imagecreatefromstring [function.imagecreatefromstring]: Empty string or invalid image


The most likely reason for this would be that the image that you retrieved from the database was either formatted wrong or most likely in your case -- the string that you passed the imagecreatefromstring() function was null or empty.

Look back over your code and make sure that you are getting the image and using the base64decose function before passing it.

Author: andrew | Website URL: www.efreelearn.com |
Hi I have used this code to store and retrieve images.
Insertion happened successfully...but while I am selecting I could not view the image.

I can view a corrupted image.


Re: Admin

Could be the gd library module in your PHP installation. When retrieving an image and displaying it you can either write a piece of code to send the proper headers to your web browser or you could just recreate the image into your file system, as a temporary file and link to it with regular HTML. The latter probably incurring more of a performance hit.
Author: andrews | Website URL: www.efreelearn.com |
Hi I used the given code to insert and view images.Insertion when successfully but when i view I get only a corrupted image like [X] .Please help
, filesize $testpic
fclose $handle

Re: Admin

Did you create an html page and point your " img src " to the page where the image retrieval code is living? Have you checked your PHP install for gd support? are you certain that you retrieved anything from your database? Look in your database and make sure the image got saved. You should see a string of charcacters. That is the bas64encoding. when you take that back of your database you will convert it back to a string and pass that into an image creation function.

$db_img = base64_decode($db_img); //print_r($db_img );

$db_img = imagecreatefromstring($db_img);

header("Content-Type: image/jpeg");



point your img src tag to the file that has the file retrieval code.

img src=location of img retrieval code
Author: Ushang Thakker | Website URL: www.smartsoftwares.tk |
when i navigate to test02.php i get this error
Warning: imagecreatefromstring [function.imagecreatefromstring]: Data is not in a recognized format

when i printed the $db_img i got :

please help urgent

Re: Admin

make sure you used the base64_decode function before the imagecreatefromstring
Author: kam | Website URL: |
steps to store image to mysql by php
Author: Delly | Website URL: |
Greetings, I m trying to create a website to display my photographs. I d like to create a kind of image gallery with thumbnail that can be clicked and then open the large image. Please Whats the best way to get along this? Cheers, Drelly
Author: iqra | Website URL: http://www.watchlivestreaming.org |
thats cool ...can you please upload for showing image on webpage?
Author: mahesh | Website URL: localhost |
good really helpful....
Author: Novella | Website URL: |
Hi Someone in my Myspace group shared this website with us so I came to
check it out. I m definitely loving the information. I m bookmarking and
will be tweeting this to my followers Great blog and outstanding style and design.
Author: Franky | Website URL: http://www.facebook.com/profile.php?id=100003427768725 |
100 free dating I am rellay enjoying the theme design of your blog. Do you ever run into any browser compatibility issues? A couple of my blog audience have complained about my blog not operating correctly in Explorer but looks great in Firefox. Do you have any recomm
Author: PHP Mysql Training Institute in Bangalore | Website URL: http://www.inspiregec.com/php-mysql-training.php |
I never seen this type of website sharing, its really great work done also its very useful to us thank you. code is very good.