Upload an image and store in database using php code

Introduction

In this article, step by step we will see php code example to how to upload an image and store that uploaded image path in mysql database using PHP code.

Step 1 : Create a simple HTML form

In step 1, let's create a simple HTML form.

 
<form action="saveimage.php" enctype="multipart/form-data" method="post">

<table style="border-collapse: collapse; font: 12px Tahoma;" border="1" cellspacing="5" cellpadding="5">
<tbody><tr>
<td>
<input name="uploadedimage" type="file">
</td>

</tr>

<tr>
<td>
<input name="Upload Now" type="submit" value="Upload Image">
</td>
</tr>


</tbody></table>

</form>

As you see from our above code that we have created a simple form which consist of input:file and input:submit button.

Make Proper use of Form Attributes

To upload any image file, It is mandatory to set following attribute as, enctype = "multipart/form-data" and action="a target path where form-data will be posted" before submitting it to the server and this is only applicable in HTTP method = "post". These attributes is available in "form" tag. So while uploading any image file make sure you have set those above attributes properly.

Since we will be using PHP scripting language to save an image to the server therefore in the "form-action" attribute we will use file with ".php" extension.

Step 2 : Create MYSQL Database Table

To create a database table, we need to write a mysql query. If you want you can use "phpmyadmin" an interface to create tables or database.

 
CREATE TABLE images_tbl(
   images_id INT NOT NULL AUTO_INCREMENT,
   images_path VARCHAR(200) NOT NULL,
   submission_date DATE,
   PRIMARY KEY (images_id)
);

As you see from above the screen shot that we have successfully created a table called "images_tbl" with columns "images_id" as

Primary Key, "images_path" to save image path and "submission_date" to note the image uploaded date.

Step 3 : Create MYSQL Connection in PHP

We will create a new php file for the connection and lets name it as "mysqlconnect.php". So lets write mysql connection.

Code in "mysqlconnect.php" file.

 

We have used "mysql_connect()" function to connect mysql and "mysql_select_db()" function to connect to particular database.

Step 4 : Store Image in Database using PHP

To store uploaded image path in database we will create a new php file name it as "saveimage.php" because in the "form" tag we gave "action" attribute target path as "saveimage.php" and in this file ("saveimage.php") all the form-data will be posted.

Let's Code "saveimage.php" file.

First lets include the mysql connection file in top of "saveimage.php" file.

 


Second let' write a simple function which will give us the image extension from a image type because there are different image types available to upload like"jpeg, gif, png, bmp" etc. So we have to create a simple function which will return us the image extension depending on the image-type.

 

Kindly Note : If you want to save an image with new name then only use the above function other wise you can also get uploaded image name with extension by using the global PHP $_FILES["uploadedimage"]["name"] variable.

In this example we will be storing an image with new name so we will be using that above "GetImageExtension()" function.

Let's store an Image in database with new name.

Complete Code in "saveimage.php" file to Store an Uploaded Image in Database

 
 ".mysql_error());  
	
}else{

   exit("Error While uploading image on the server");
} 

}

?>;

If you don't want to use the new image name you can replace the following code as shown below.

 


About move_uploaded_file()

move_uploaded_file() a php inbuilt function which helps us to upload any image or file to the server. It takes input as file name and target source destination.

move_uploaded_file (string $filename , string $destination)

If you see in our above that we have called our insert mysql query only when move_uploaded_file() function uploads the file successfully to the server other wise exit with an error.

When move_uploaded_file() upload the file to the server that time we have called mysql insert query on table "images_tbl" to store the image name and path from "$imagename" variable and submission_date as today's server d by using date by using php date() function.

Step 5 : OUTPUT : Display Image From Database using PHP

 



" alt="" />">

This is all about the php image uploading and storing it in the mysql database. If you like this article kindly share it with your friends and want to comment please let me know through you comments. Thanks

Author: Gurunatha Dogi

Gurunatha Dogi

Gurunatha Dogi is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server and lots more..... read more

Comments

64x64
By Neha on 2019-02-21
Thank you, its very helpful for me.
64x64
By Vena on 2016-06-03
Thank you. It help me alots
64x64
By Souvik on 2016-06-01
i try this i think there something wrong first is in html code there is no browse button.. and in the saveimage.php there also some wrong
64x64
By Aaryan on 2016-05-30
wow, its easy for beginner ,thanks
64x64
By Randika on 2016-04-25
Thank you very much !!!!
64x64
By Alumansi on 2016-02-24
Thanks for that code.it has actually simplified my work
64x64
By Nag on 2016-02-23
Very Helpful. thank you brother
64x64
By Srujana on 2016-01-30
good article
64x64
By Rajeev Kumar Suman on 2016-01-27
plz give a example using mysqli query to insert data image in database.
64x64
By Joanvillafuerte on 2016-01-23
I tried the codes above and a Parse error: syntax error, unexpected '=' on line 40 in my save image.php
64x64
By Qayum on 2015-11-07
Its fantastic guidance thanks Gurunatha
64x64
By Yadav on 2015-10-21
how to create a txt file in the random number folder using php
64x64
By Rasika on 2015-09-22
Thanks a lot dear... it helps me a lot... really thanx... :)
64x64
By Engineers on 2015-09-03
Love you bro... Good start for beginners like me... :)
64x64
By Hgfghf on 2015-08-19
Still there is a little syntax error on this code..... on step number 5 in line 14
64x64
By Neha bhatt on 2015-06-25
hi there is a syntax error in 5 step in line 14..plz solve it
64x64
By Neha on 2015-06-24
i hv a syntax problem in step 5 in line 14 img src..pls solve it
64x64
By Narendra on 2015-06-23
how to upload images into database and display the image
64x64
By Shyam singh on 2015-06-11
very simple code so much, thanks you...... sir
64x64
By Suhbah on 2015-05-19
how the coding will be if the different users adding same file
64x64
By Praveen on 2015-04-03
Excellent Work Good Job...
64x64
By Jagdish on 2015-03-29
Thanks for provide superb guide....
64x64
By Aamir Ali on 2015-03-16
Good Explanation...I have learnt from this page a lot..Thanks a lot.
64x64
By Shahid on 2015-03-12
is that posisblle that uploaded images will go into the image folder as well as categories wise folder
64x64
By Sonia on 2015-01-30
Hi. What if the image is missing from the database after Updating? For example I have a form where user can edit anything on the form e.g name, image, address etc but doesn't want to edit/upload a new image. But after clicking "save" button and viewing his/her form, the image disappears or missing. Can you help with that? Please email me if there is any update on this at saminbhp@gmail.com Thanks
64x64
By Minha on 2015-01-18
In display images from database using php
64x64
By Kothai on 2015-01-13
Thank Yu..It works well..
64x64
By Behzad on 2015-01-07
Thanks for great informations... GOOD LUCK..
64x64
By Udaiyar on 2015-01-07
how to store video in one folder using php
64x64
By Jeeve on 2014-12-27
why didnot store image in floder, i need help ,so pls help to me my souce code below
64x64
By Sadaf ali on 2014-11-20
made my work simple.thanks for sharing
64x64
By مهدی on 2014-11-19
Thank you so very much
64x64
By Ivan mbuyah on 2014-10-25
Still there is a little syntax error on this code..... on step number 5 in line 14
64x64
By Dipinraj on 2014-10-17
Thank you for the code , It worked for me !!! . Could resolve it after same errors in Syntax. I think the error was occurring due to single quotes of fields in insert....@L31 Since im a newbie im not sure if this is the issue.Anyways workd for me.
64x64
By Randy on 2014-10-10
You using old mysql syntax instead of mysqli or pdo. Any good reason for that?
64x64
By Sushil kant triathi on 2014-10-09
hi this script is working for all type of file there is no validation for img
64x64
By Ramalingam P on 2014-10-01
It's very help to learn for beginners.. Thanks
64x64
By USL on 2014-09-26
Hi. This script uploads any type of file. Is there a way to restrict it to only image files? Thanks
64x64
By USL on 2014-09-26
Hi. This script uploads any type of file. Is there a way to restrict it to only image files? Thanks
64x64
By Umang on 2014-09-18
Please Send me code of displaying image,above code does not work
64x64
By Tushar Gupta on 2014-09-14
Working Fine On local But Error showing when i am using this on server.. Error was - 500 - Internal server error. There is a problem with the resource you are looking for, and it cannot be displayed.
64x64
By Mps on 2014-09-05
i m facing the syntax error on my side.. plz advice
64x64
By Toy on 2014-09-04
thanx for tips ...give another tips how to make data base file show in html page like highest price to lowest and lowest price to highest. thanx again
64x64
By Muhammad Bilal Haider on 2014-08-30
$query_upload="INSERT into images_tbl ( images_path , submission_date ) VALUES ('".$target_path."','".date("Y-m-d")."')";
64x64
By Kathleen povadora on 2014-08-29
GUYS! from the bottom of my heart, Thank you! All statement above works, so easy to follow and understand! Thank you and God bless! Keep helping developers guys :)
64x64
By Mehul patel on 2014-08-29
thanks
64x64
By Jay on 2014-08-29
help me, i always had error in this line " height="100" width="100" but the image is not displaying .it will only display the border of height="100" width="100" help me
64x64
By Rian on 2014-08-27
can you help me. i just got an error at this line and i don't know why.. Warning: move_uploaded_file(images/27-08-2014-1409129702.png): failed to open stream: No such file or directory in C:\Users\user\Desktop\xampp\htdocs\keje\saveimage.php on line 29 Warning: move_uploaded_file(): Unable to move 'C:\Users\user\Desktop\xampp\tmp\phpFED3.tmp' to 'images/27-08-2014-1409129702.png' in C:\Users\user\Desktop\xampp\htdocs\keje\saveimage.php on line 29 Error While uploading image on the server
64x64
By Aimelo Malisa on 2014-08-26
can I have a source code?? downloadable i mean! Thanks..
64x64
By Shyaka on 2014-08-25
thx
64x64
By Csdfdsf on 2014-08-22
good
64x64
By Shakiralikhan on 2014-08-20
mast
64x64
By Manju on 2014-08-19
good one.. u deserve a wow..
64x64
By Nkosinathi on 2014-08-18
I found your scripts very useful, I will use it for employee signatures. I only found problems with the output code but I think i will figure it out. its not working properly on line /14...
64x64
By Michael john pinza on 2014-08-14
how to I fixed these error?? "error on INSERT into 'images_tbl' ('images_path','submission_date') VALUES('img/14-09-2014-1410664188','2014-09-14') == ----> You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''images_tbl' ('images_path','submission_date') VALUES('img/14-09-2014-1410664188' at line 1" PLz help me plz
64x64
By Nkosinathi on 2014-08-12
Its great code
64x64
By Raj on 2014-08-11
good
64x64
By Babloo on 2014-08-09
Data base upload a image in my Project
64x64
By Abdul on 2014-08-05
Am having sytnax error at this line
64x64
By Sanjay on 2014-08-04
nice
64x64
By Ngugi Ndung'u on 2014-07-24
I really love the way you are explaining even befor I have a look on it. I think the site will help me a lot.
64x64
By Sadiqa on 2014-07-13
wawo it really helped me in my project thanks buddy .... :)
64x64
By KIm on 2014-07-10
Wow !!!! This is just what I was looking for my assignment. Thank you and God bless you. How can you use a simple JSON web service that can be used to retrieve the title, description, filename, width and height of the image that has been uploaded to the application. The data should be returned from the service. Any Idea ? Thanks again.
64x64
By Kim on 2014-07-06
does it apply to xamp coz am recieving this error...error in INSERT into 'images_tbl' ('images_path','submission_date') VALUES ('images/06-07-2014-1404644316.bmp','2014-07-06') == ----> You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''images_tbl' ('images_path','submission_date') VALUES ('images/06-07-2014-14' at line 1
64x64
By Ab on 2014-07-04
I wanna assure that the image is saved, in which folder by default these images get saved??
64x64
By Admin on 2014-07-02
@Gayathri, Sure will do that anyways thanks for posting your comments
64x64
By Gayathri on 2014-07-02
I can able to upload the image but while performing edit its not working can u pls send me the code foe edit and update the image ... regards, gayunattu
64x64
By Admin on 2014-07-02
@Poojan Shah, Kindly check the folder permission..Folder permission should be 0777 Thanks
64x64
By Poojan Shah on 2014-06-30
Hello thank you for your help but the code is not working . While uploading the image I am getting error for move_uploaded_file. kindly help me out.
64x64
By Karar Barcha on 2014-06-19
Hello Sir, Please Help me for my project, i am student of CS, so i am working on a project. My project title is "Daily K2" ePaper, (online news paper, using jpg in body). so first of all i need interface which i have designed using html and css, now i need Database (wamp server) and php code for inserting news paper image with date, and also display that jpg with date. i have four pages of news paper with jpg imag in main body which must insert is database in every day by day, and must display with date..... I also need to facility to display previous papers with date...... Please help me in my project sir Am waiting for your Message Karar Barcha (kararbarcha@gmail.com)
64x64
By Rajitha Madushan on 2014-06-14
Nice article Guru... great work. it is worked for me...perfectly. good work Carry on..
64x64
By Shanavas R on 2014-06-11
Excellent work
64x64
By Idris on 2014-06-09
Nice work>>>>>>>>>>>>>>>>> thanks
64x64
By Admin on 2014-05-27
@saman....You have used single quote on table and column names instead of single quote use ` grave ascent
64x64
By Saman on 2014-05-25
this does not work why??
64x64
By Saman on 2014-05-25
error in INSERT into 'images_tbl' ('images_path','submission_date') VALUES ('images/27-05-2014-1401208852.jpg','2014-05-27') == ----> You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''images_tbl' ('images_path','submission_date') VALUES ('images/27-05-2014-140120' at line 1 -----what is the mistake here???? that i have done---
64x64
By Henry on 2014-05-08
nice tutorial for uploading picture and save its image in folder not directly in database, thanks mate :)
64x64
By Enos mabula on 2014-05-04
I tried to upload image into database but it is returning a warining at line 22 and 29 and it says Error While uploading image on the server so please I need more help

Add a Comment