Rayhan’s blog (raynux.com)

Rayhan’s Personal Web Blog Site

Entries Comments

Store and Display image from MySQL database

20 November, 2008 (16:09) | MySQL, PHP, programming, Reference

Tags: , , , ,

A basic approach to upload and save image to a MySQL database and then display the image from the database.

First you need to create a table in MySQL Database to store the image data. Log into you database and run the following sql command:
CREATE TABLE  `images` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(100) default NULL,
`size` int(11) default NULL,
`type` varchar(20) default NULL,
`content` mediumblob,

Once the table have been created, we are ready to write codes. Now create a folder in you webserver named rayImg and create image.php and upload.php files inside the folder.

Open the image.php, copy and paste the following code and save it.

File: image.php

	 * Display image form database
	 * Retrive an image from mysql database if image id is provided.
	 * @example to display a image with image id 1, place <img src="image.php?id=1" > in your html file.
	 * @author Md. Rayhan Chowdhury
	 * @copyright www.raynux.com
	 * @license LGPL

	// verify request id.
	if (empty($_GET['id']) || !is_numeric($_GET['id'])) {
		echo 'A valid image file id is required to display the image file.';

	$imageId = $_GET['id'];

	//connect to mysql database
	if ($conn = mysqli_connect('localhost', 'root', 'root', 'test')) {
		$content = mysqli_real_escape_string($conn, $content);
		$sql = "SELECT type, content FROM images where id = {$imageId}";

		if ($rs = mysqli_query($conn, $sql)) {
			$imageData = mysqli_fetch_array($rs, MYSQLI_ASSOC);
		} else {
			echo "Error: Could not get data from mysql database. Please try again.";
		//close mysqli connection

	} else {
		echo "Error: Could not connect to mysql database. Please try again.";

	if (!empty($imageData)) {
		// show the image.
		header("Content-type: {$imageData['type']}");
		echo $imageData['content'];

Now open the update.php, copy and paste the following code and save it.

File: upload.php

 * Upload an image to mysql database.
 * @author Md. Rayhan Chowdhury
 * @copyright www.raynux.com
 * @license LGPL

// Check for post data.
if ($_POST && !empty($_FILES)) {
	$formOk = true;

	//Assign Variables
	$path = $_FILES['image']['tmp_name'];
	$name = $_FILES['image']['name'];
	$size = $_FILES['image']['size'];
	$type = $_FILES['image']['type'];

	if ($_FILES['image']['error'] || !is_uploaded_file($path)) {
		$formOk = false;
		echo "Error: Error in uploading file. Please try again.";

	//check file extension
	if ($formOk && !in_array($type, array('image/png', 'image/x-png', 'image/jpeg', 'image/pjpeg', 'image/gif'))) {
		$formOk = false;
		echo "Error: Unsupported file extension. Supported extensions are JPG / PNG.";
	// check for file size.
	if ($formOk && filesize($path) > 500000) {
		$formOk = false;
		echo "Error: File size must be less than 500 KB.";

	if ($formOk) {
		// read file contents
		$content = file_get_contents($path);

		//connect to mysql database
		if ($conn = mysqli_connect('localhost', 'root', 'root', 'test')) {
			$content = mysqli_real_escape_string($conn, $content);
			$sql = "insert into images (name, size, type, content) values ('{$name}', '{$size}', '{$type}', '{$content}')";

			if (mysqli_query($conn, $sql)) {
				$uploadOk = true;
				$imageId = mysqli_insert_id($conn);
			} else {
				echo "Error: Could not save the data to mysql database. Please try again.";

		} else {
			echo "Error: Could not connect to mysql database. Please try again.";

		<title>Upload image to mysql database.</title>
		<style type="text/css">
				margin: .2em;
				border: 1px solid #555;
				padding: .2em;
				vertical-align: top;
		<?php if (!empty($uploadOk)): ?>
		  		<h3>Image Uploaded:</h3>
				<img src="image.php?id=<?=$imageId ?>" width="150px">
				<strong>Embed</strong>: <input size="25" value='<img src="image.php?id=<?=$imageId ?>">'>

		<? endif; ?>

		<form action="<?=$_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data" >
		  	<h3>Image Upload:</h3>
		  	<input type="hidden" name="MAX_FILE_SIZE" value="500000">
			<input type="file" name="image" />
		    <input name="submit" type="submit" value="Upload">

Replace line

mysqli_connect(‘localhost’, ‘root’, ‘root’, ‘test’)


mysqli_connect(‘your host’, ‘your username’, ‘your password’, ‘your database name’)

in both the file and save again.

You are done. Open upload.php from your browser and upload you desired image and view the uploaded image.




Comment from stathis
Time: January 20, 2009, 3:37 pm

can u help me i done all and i saw that msg :

You don’t have permission to access /rayImg/< on this server.

Comment from rayhan
Time: January 28, 2009, 5:30 pm

@stathis can you give me some details.

- first you have to run the code from a server like apache with php enabled. I think you did it.
- Check for writing mistake or try copy and pasting the code.
- “/rayImg/< " is not a valid path,
- Path should be http://localhost/rayimg/upload.php for upload file
- or
http://localhost/rayimg/image.php?id=223333 for image display file.

Please check the following and let me know if you have any same problem.


Comment from A
Time: February 12, 2009, 11:45 am

I have seen several scripts on the net for uploading images to a database and understand that some use some kind of temp image on the server while uploading that can cause conflicts if more than one user is trying to upload at the same time. Does your script have any similar issue that might need to be addressed.

Thanks for any info!


Comment from A
Time: February 12, 2009, 11:37 pm

I tried your script and it seems to be working except when I upload a file greater than 500k I get an error saying “Error: Error in uploading file. Please try again.” instead of “Error: File size must be less than 500 KB.” When I try to upload a file with an incorrect extension, however, I do get the correct error message. Any idea what is happening. Also …

just a note nothing would work at first, as something strange goes on when I copy and paste the code from your web page into Dreamweaver. It had the wrong encoding and I had to replace all the commas and quotation marks within Dreamweaver, or the files would not work when saved and uploaded to my server.



Comment from rayhan
Time: February 17, 2009, 4:27 pm

@ A
— it’s an approach to show how to handle image file uploading to a database, not a solution for all scenario.

Regarding Error Message:
it’s ok, check your server upload limit may be lower than 500k.

Regarding Encoding:
well, it might happen…try pasting the code to wordpad….

Regarding temp image:
nope, there should not be a problem with multiple users…


Comment from G.S.Piash
Time: March 14, 2009, 8:30 pm

when I’m trying to upload a picture then i’ve faced this “Forbidden

You don’t have permission to access /php/< on this server.”
and in the address bar “http://localhost/rayhan/”.
Can you help me to prevent this problem??

Comment from Mag
Time: March 30, 2009, 4:44 pm

It’s a great tutorial, thanks I could get it work but now my problem is how to display the uploaded image to my index ( or other ) page. Can you help.


Comment from rayhan
Time: March 30, 2009, 8:42 pm


It’s good to know that you made it working. using image.php file provided here you can easily show your uploaded image. Instructions are given in the comment section of the image.php.

Detail Instructions:
open your browser and point to http://yourdomain/path/image.php?id=1, this will show image from the database with record id = 1, replace 1 with your desired image id in the database.

In your index page add <img src=”http://yourdomain/path/image.php?id=1″ /> to show the image from the database with record id = 1, replace 1 with your desired image id in the database.


Please check your code. I think it’s an encoding problem. Check the comments of A:

Hope this will solve your problems.


Comment from Mag
Time: March 31, 2009, 1:42 am

Hi again, thanks a lot it works perfectly now. What if I want to upload Flash files (swf extension) how do I do that?

Thanks in advance

Comment from Mag
Time: March 31, 2009, 1:46 am

Ups I had another Q. how can I display only the last uploaded image on my index page?

Thanks again

Comment from rayhan
Time: March 31, 2009, 9:48 am


- For displaying latest image, you can modify image.php file and pass a variable latest=1. like image.php?latest=1
- then add a sql to get last id from the database
- change $imageId = $_GET['id']; with the latest id extracted from database.


if (isset($_GET['latest']) && $_GET['latest'] == 1) {
$imageId = latest id got from database.
} else {
if (empty($_GET['id']) || !is_numeric($_GET['id'])) {
echo ‘A valid image file id is required to display the image file.’;

$imageId = $_GET['id'];

solve like that way.

regarding Shockwave flash file upload, modify the line
if ($formOk && !in_array($type, array(‘image/png’, ‘image/x-png’, ‘image/jpeg’, ‘image/pjpeg’, ‘image/gif’))) {

add shockwave flash mime type in the array. hope this will solve your problem.


Comment from Mag
Time: March 31, 2009, 2:25 pm

Hi Rayan, when I copy paste the code you sent me for the latest showing image it does not work…..Do I need to change something on my index as well?

About uploading swf files I inserted ‘image/swf’ but it says -not supported file format (or similar)

Can you help


Comment from GIna
Time: April 4, 2009, 8:39 pm

I keep getting this error. Does anyone know why? Thank you.

p.s. The PHP Version 5.1.4

Fatal error: Call to undefined function mysqli_connect() in c:\Project\htdocs\upload.php on line 43

Comment from rayhan
Time: April 5, 2009, 10:15 am


There are two extensions in PHP to connect to MySQL server. These are mysql and mysqli (improved mysql).

This error indicates that you don’t have mysqli extension installed in your system. you can install mysqli extension or modify all mysqli function with corresponding mysql functions.


Comment from Masko
Time: April 20, 2009, 1:24 am

have a problem dont know if is from site or other stuff, but when try to upload an image bigger than 500 kb the image store, but cant display it :/ the image shows like a broken link

// check for file size.
if ($formOk && filesize($path) > 500000) {
$formOk = false;
echo “Error: File size must be less than 500 KB.”;

at that section changed the 500000 for 2000000 because wanted images from 2 Mb but any image over 500 kb cant be displayed any help?

thank you :)

Comment from Masko
Time: April 20, 2009, 5:16 am

mmm think the problem solved by itself maybe was something from server dont know sorry :p thank you and great tutorial ^^

Comment from Ese
Time: May 17, 2009, 12:10 am

I want to use CSS and javascripts to render an image displayed with . Does any one have a sample of such codes or an idea on what to be done? My present images remain static. This is not fashionalble enough. Thanks
Ese Edward from Finland.

Comment from Ese
Time: May 17, 2009, 12:13 am

displayed with < img src=’myfile.php’ > . Sorry, this part could not go, now I put it in this way.

Comment from MD. RAJIB HOSSAIN
Time: May 29, 2009, 12:17 pm

Thanks Brother this code bring me one step ahead. My name is Rajib From BANGLADESH.

Comment from benny adar
Time: June 2, 2009, 7:05 pm

how come i don’t see the photos?
everything is ok in the mysql table but i still don’t see the photos.
where are the photos uploaded to?
i’m using php 5.2.4, mySQL 5.0.45, IIS 6.0
will appriciate any reply
thank you

Comment from Ata
Time: June 10, 2009, 8:05 pm

thanx for the code really nice!
One question, when i want to display the image does it have to be in a *.html file??
because i tried to display the image in my database in an php file but i got the message: “A valid image file id is required to display the image file.” but if i put the same code in an html file it works and loads the image!
What am I doing wrong??
Thanx man!

Comment from onur
Time: June 14, 2009, 11:43 pm

hi my friend. thank you! =)

Comment from victor
Time: July 14, 2009, 4:42 pm

Copy pasted, only your upload.php works “as-is”. In addition to printing the binary data of an image to image.php, php also prints an error message concerning line 24…..such that the integrity of image is brokwn and cannot be displayed.
To fix it, I simply commented that particular line, and it worked [....finally ending a whole morning(6.5hrs) spent searching for code like yours.]
The line am talking about is this:

**$content = mysqli_real_escape_string($conn, $content);

According to php, the use of “$content” in the mysql function is invalid as it hasn’t been declared yet…..or something to that effect. I guess its coz at that moment $content is still empty.

So whats the purpose of that particular line of code?

Comment from victor
Time: July 14, 2009, 7:16 pm

…..actually, upload.phph only “kinda” works copy pasted. It correctly uploads the a file, but doesn’t correctly call the image via image.php directly [at least it does so on my server]. The fix is really simple: just edit the php to correctly echo the right id and in the right format. So instead of [in upload.php]:
**<img src="image.php?id=” width=”150px”>
<img src="image.php?id= ” width=”150px”>

….by the way, thanks a zillion times for this post dood. I spent a whole morning trying to work out other people’s code who insisted that their code would work copy-pasted just like that [including creating the relevant table for u...i.e creating the table if an error occeurs trying to select if after a successfull connection to the database].

Comment from rayhan
Time: July 15, 2009, 10:05 am


The code is tested and run by some other people without any fix. It should work in your server too…

May be there are some problem with your server configuration.

Instead of line
<img src="image.php?id=<?=$imageId; ?>" width="150px">

You can also write normal php echo code:
<img src="image.php?id=<?php echo $imageId; ?>" width="150px">

Thanks for your input. It may help some other people to make it workable.

Comment from jerome
Time: July 16, 2009, 1:12 pm

Hai Rayhan,
Thanx a lot man…your code worked like a cake and saved my time …keep going man……

Comment from jerome
Time: July 16, 2009, 1:15 pm

hai rayhan

It’s my kind suggestion to have the edit feature in comments section.Bcoz its very handy if it is.

Comment from kumbi
Time: August 13, 2009, 4:41 pm

rayhan, i’m trying to use your code to display all the images in the database, by default, on images.php. how do i go about modifying it?

Comment from Ammar Bin Nawab
Time: August 21, 2009, 6:43 pm

Thanx Rayhan for ur script. please, help me. suppose in index.php, there are more images(more than 1000). images are uploaded in mysql database. when some one click on one image , the image and its information will be displayed at display.php from database. i need such script. 01919478253

Comment from Kevin
Time: September 6, 2009, 1:21 am

I copied the codes as you suggested, placed them in the relevant files and changed the database info in both files. This is all I get when I try to access the form:

Parse error: parse error in C:\wamp\www\rayImg\upload.php on line 99

Comment from Sander
Time: September 16, 2009, 12:14 am

I’ve used your script. Everything is working fine, except displaying the image.
It’s not dispaying a image at all, if I look at the image’s URL it says: http://localhost/mapname/rayImg/image.php?id=21
How come I’m not seeing the image?

I hope you can help

Grz Sander

Comment from Ryan
Time: September 23, 2009, 1:59 am

hi Rayhan
I am self studying php and mysql and wanted to learn how to upload pic to my mysql database. I did as u said on top and when i run the upload.php i get a blank or empty page as if nothing is happening instead of displaying me the upload field.
I have created the table in mysql as u said.

Can u please help me out.


Comment from momo
Time: October 15, 2009, 1:42 pm

i got error like this in ur upload.php

Parse error: syntax error, unexpected $end in C:\xampp\htdocs\e-LI\upload.php on line 99

i dont know why
i hv tried check the code
but it seems nothing wrong
can u please help me with this
tq :)

Comment from raja
Time: November 13, 2009, 12:49 pm

fine. very nice. It is very useful

Comment from gegejosper
Time: November 23, 2009, 1:45 pm

thanks for your tutorial..can you ad on how to display multiple images save in the database?

Comment from abcd
Time: February 10, 2010, 12:35 am


nice and useful blog…

as i m facing with a problem in my work i thought to ask here…

i hv uploaded files with mb size and stored them in database…then i m retrieving them from database…bt i cant see images in IE…and its working on firefox better…its on local server…

on live server…after submit to disp details,i m getting “webpage has expired”…in IE7 and firefox works better…

can anyone tell me what can i do?

Comment from cams
Time: March 15, 2010, 9:29 pm

Your script is mindblowing. I spent a lot time on searching of image uploading and showing. this is really helpfull for me. thank a lot

Comment from sathiya narayana
Time: March 31, 2010, 6:38 pm

Hi friend
its working well
Thanks a lot it help me project of major part

Comment from sathiya narayana
Time: March 31, 2010, 6:40 pm

good work
thanks for publishing code
it really helps!…

Comment from sskt
Time: June 22, 2010, 3:11 am

I have the same code in my vbulletin forums. but statement
echo $rock=”";
does not display anything in IE. what am I doing wrong? Any IE settings to be changed ?? or is it a version problem?

Comment from ravi
Time: July 24, 2010, 5:10 pm

i used this code.code is working but problem is that it doesn’t show image just show image place….wht to do plz help me

Comment from fdgdfg
Time: October 12, 2010, 1:23 am

nice site

Comment from ans
Time: October 28, 2010, 7:44 pm

Parse error: syntax error, unexpected $end in C:\xampp\htdocs\raylmg\upload.php on line 86

IM GETTIN THE above error and at line 86 is

Comment from kmkmahesh
Time: January 19, 2011, 10:18 pm

can i know where the image file will be uploaded

Comment from rayhan
Time: January 20, 2011, 12:07 am

Yes, the image is being uploaded to the database.

Comment from Ramya
Time: March 12, 2011, 10:25 am

I used this code.the code is running.but it does nt show the image.it shows the image path only

Comment from sam
Time: March 15, 2011, 4:46 pm

Parse error: parse error in C:\wamp\www\rayImg\upload.php on line 99

can u help with this error plz

Comment from JN
Time: March 23, 2011, 10:56 am

I’d like to know if you can do a custom script for me and how much you charge,

db for user profile
db for user imgs
db for html, css, txt file upload
db for unique visitor counter were show IP, Os, Browser, IP location, and track visitors and user
a loop header for the index page were the text and the bg img will keep rotating …
also a random page for the index body were evry time will show a randon index page.
a user registration, log in a admin systeam , were user can view other user, send messages, add user, upload files, img,htmt, css, txt to a db, the admin page were show all The Ip information tracking, add, remove,edit, approve user, for more detail contact me I now you have most of this done if you can just need the script . let me know OK

Comment from manish kumar
Time: August 10, 2011, 4:01 pm

its Awesome man!

Comment from usha
Time: August 25, 2011, 2:58 pm

Hi Rayhan,
I go through the instructions what ur giving in above code.i uploaded image to database but i am unable to see image can u help me out plz,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,i am able to see the image type but not image

Comment from HIREN
Time: August 30, 2011, 5:53 pm


Comment from Naeem
Time: September 8, 2011, 10:09 pm

Rayhan your script is not working properly

Comment from kiko
Time: September 25, 2011, 3:29 pm

hi. I want upload two images at the same time and same mysql table. please help somebody :-)

Comment from vinayaka
Time: October 25, 2011, 4:41 pm

Great code.saved a lot of time.Thank u.

Comment from new leaner
Time: October 27, 2011, 12:53 am

I am tired to run your code because I can not understand how to display all images on pages >>

can you give us an example by php and MySQL, how can we display many image on page I mean how can we retrieve all images and description

Comment from pramod
Time: November 8, 2011, 12:16 am

Thank You very much……

Comment from sHUBHAM
Time: November 24, 2011, 9:13 pm

I want a code through which i can upload multiple images at a time,i mean to say dhat if i click brows button once then i should be able to select multiple images and upload all to a folder and store there path to a database.
please help me.

Comment from ishrat
Time: November 27, 2011, 11:01 am

the code is working but it shows a broken image. i really dont know whats wrong. please can anybody tell me?

Comment from ibrahim
Time: December 3, 2011, 2:06 am

i have done every thing about this tutorial but the image is not displaying on my web page, i am wondering does the image has to be on my server because i thought when i upload the image from my computer it should upload to the server directly

Comment from Pete
Time: December 7, 2011, 9:42 am

Great couple of scripts there. I have an interesting challenge.

I use the excellent graph plotting library called phplot. I use it with DrawGraph(); method to generate the output.

I’m trying to capture the output so that I can cache it into a MEMORY table in MySQL rather than regenerate the chart lots of times (it changes only once per day).

I’ve used the PHP serialize() function to store arrays of data in MEMORY table and it works incredibly well (so fast) no matter how big the array so I’m hoping that storing small 4KB images would be a great way of gaining performance.

Do you have any ideas? As you can see I’m not bringing an image file in from a standard input source but rather generating it. I’ve tried serializing the $graph object before the DrawGraph() method and can’t get it to work.

Maybe this could be the topic of a future blog? Can you help.


Comment from rayhan
Time: December 7, 2011, 10:27 am


Two way you can get the image from DrawGraph() method.

1) you can save the image from DrawGraph() method to a file and store it into database.
2) you can get the image string as return value from DrawGraph() method instead of directly showing it into the browser

Hope the hints will work.


Comment from gopu
Time: December 8, 2011, 5:24 pm

Parse error: parse error in C:\wamp\www\rayImg\upload.php on line 99
plz anyone help me out of this error…..

Comment from Parwinder Singh
Time: December 8, 2011, 6:51 pm

any body help me yr
plz tell me how can save and retrieve image on php
plz yr
any body help me call me 9023233670

Comment from Sarah
Time: December 8, 2011, 9:41 pm

hi every thing work fine but image is not show after upload , i did check in data base its added but its not showing on upload.php, :( can you help me urgent

Comment from Sarah
Time: December 8, 2011, 10:22 pm

i need to add image name and its short description can you help me out i did try to insert the name2 ( name of the image ) but its give me this error “Error: Could not save the data to mysql database. Please try again.

i just need to add name of the image like ABC and its short description,

i am waiting for ur reply

Comment from vaisakh
Time: December 23, 2011, 2:29 pm

Nice work,It helped me a lot

Comment from NEW to PHP need Help Urgently
Time: December 29, 2011, 3:39 pm

Embed: <input size="25" value='<img src ="image.php?id=”>’>

Is something wrong with my syntax. I uploaded image to mysql (It shows in my Database) using the code but the image don’t display correctly. A block where the image should display with red cross display and in my Embed textbox this display .

Can you please help me? I’m new and confused.

Comment from Thewolf
Time: January 2, 2012, 7:00 pm

Very helpful, thewolf

Comment from vineet
Time: January 14, 2012, 1:24 am

your code really work . thanks for ur code its save bunch of my time . its copy paste and work ..

Comment from Aritra
Time: February 16, 2012, 11:05 am

First of all I would like to thank you for your efforts. I tried uploading the image to my test database table ‘images’,which I have created as u’ve mentioned. I just changed the content-string to ‘LongBlob’ and in the upload.php file changed the max. file size to 5 MB. Now, whenever I try uploading an image less than 1 MB, it shows the error message “Error: Could not connect to mysql database. Please try again.” . Now, if I try uploading a larger file, it shows the error message “”Error: Error in uploading file. Please try again.” I’m a little confused, it will be real helpful if you focus on this matter… with regards, aritra.

Comment from Aritra
Time: February 16, 2012, 11:14 am

Well, I figured out the problem myself, there was some problem in my query. Thanks again, great job done.

Comment from Aritra
Time: February 16, 2012, 11:20 am

@New to PHP need Help Urgently, make sure that u’ve mentioned the right database and table name in the file image.php… :) )

Comment from Coder
Time: March 6, 2012, 1:35 pm

The script is great..pls tell me can we place the code in one file?
when i placed all the code i got the error.

Comment from sankari
Time: May 29, 2012, 10:14 am

the image is does not display but is stored in database ready.why?

Comment from covert hypnosis
Time: January 19, 2013, 5:10 pm

What’s Taking place i am new to this, I stumbled upon this I have discovered It absolutely useful and it has aided me out loads. I am hoping to give a contribution & aid other users like its helped me. Good job.

Comment from weelDaw
Time: May 6, 2013, 11:55 am

Thank’s for the code it’s very helpful to me … :)

Comment from arpita
Time: May 28, 2013, 12:57 pm

how to edit image in php and display also single image plzzzzzzzz give me code in this email id……
help me….plzzzzzzz its fast

Comment from polly
Time: June 8, 2013, 9:17 am

the code only echoes “A valid image file id is required to display the image file”. what am i going to do?
thanks. I have already uploaded images to my database but it cannot be displayed.

Comment from boopathi rajan
Time: June 10, 2013, 1:05 pm

I am self studying php and mysql and wanted to learn how to upload pic to my mysql database. I did as u said on top and when i run the upload.php i get a blank or empty page as if nothing is happening instead of displaying me the upload field.
I have created the table in mysql as u said.

Can u please help me out.


Comment from rockstar
Time: June 12, 2013, 6:02 pm

thanx 4 d code:)it works fine but display of image is not coming on d index page

Comment from briannedelagarza
Time: July 18, 2013, 9:09 pm

Really when someone doesn’t understand after that its up to other visitors that they will help, so here it occurs.

Write a comment