Upload and Save image with PHP and MySql

by  
Share:
Upload multiple images create thumbnails and save path to database with php and mysql

One of the most sought after script of all time for a PHP beginner is “upload and save image to database “. When I was in my college I always tried to store the image as a whole inside the database, but was unaware of this technique of doing the same. In this tutorial I will explain how to upload image with PHP and save it to MySQL database. Also included in this script is fetching all the images from database and display them in a list.

Scope of this script?

Using this script you can upload images (png, jpg, jpeg, gif,bmp) via php and then store their location/path in MySQL database. Also included in this script is fetching all the uploaded images from mysql database and display them as a list.

Upload Image with Php and save in MySql

Uploading images with PHP and storing it in MySQL database is a four steps process:

  • Setup a form with an image field.
  • Validate the image before uploading.
  • Upload the image with PHP.
  • Store the uploaded image path to the MySQL.

Before you proceed, make sure you have created a database and table in your mysql database server.

CREATE DATABASE  `Shahrukh` ;
CREATE TABLE IF NOT EXISTS `Shahrukh`.`tbl_demo` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image_url` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Setup a form for uploading image. Don’t forget to add enctype=”multipart/form-data” attribute, which is a common mistake most of beginners does. And always set the method to post.
<form method="post" action="" name="f" enctype="multipart/form-data" >
<input type="file" name="img_file" id="img_file" />
<input type="submit" class="submit_button" value="Submit" name="s">
</form>

You can validate the image using javascript or jquery. just add a function that will check for a valid image. Also bind the function on onSubmit event of the form.
<form method="post" action="" name="f" enctype="multipart/form-data" onSubmit="return validateImage();" >

Add this JavaScript function inside the head tag of the page.
<script src="jquery-1.9.0.min.js"></script>
<script>
function validateImage() {
	var img = $("#img_file").val();

	var exts = ['jpg','jpeg','png','gif', 'bmp'];
	// split file name at dot
	var get_ext = img.split('.');
	// reverse name to check extension
	get_ext = get_ext.reverse();

	if (img.length > 0 ) {
		if ( $.inArray ( get_ext[0].toLowerCase(), exts ) > -1 ){
		  return true;
		} else {
			 alert("Upload only jpg, jpeg, png, gif, bmp images");
			return false;
		}			
	} else {
		alert("please upload an image");
		return false;
	}
	return false;
}
</script>

If in case JavaScript is disabled on user’s computer write the code to validate the image with PHP also. Here’s the script below.
<?php
if (isset($_POST["s"])) {
  $img_file = $_FILES["img_file"]["name"];
  $validExt = array("jpg", "png", "jpeg", "bmp", "gif");
  if ($img_file == "") {
    $msg = errorMessage( "Attach an image");
  } elseif ($_FILES["img_file"]["size"] <= 0 ) {
    $msg = errorMessage( "Image is not proper.");
  } else if ( !in_array($ext, $validExt) )  {
    $msg = errorMessage( "Not a valid image file");
  } else {
    // upload script here
  }
}
?>

Now the final showdown, uploading the image to the server with PHP and then save the image path to the MySQL database.
<?php
$img_file = $_FILES["img_file"]["name"];
$folderName = "images/";

// Generate a unique name for the image 
// to prevent overwriting the existing image
$filePath = $folderName. rand(10000, 990000). '_'. time().'.'.$ext;

if ( move_uploaded_file( $_FILES["img_file"]["tmp_name"], $filePath)) {
    $sql = "INSERT INTO tbl_demo VALUES (NULL, '".prepare_input($filePath) ."')";
    $msg = ( mysql_query($sql))  ? successMessage("Uploaded and saved to database.") : errorMessage( "Problem in saving to database");

  } else {
    $msg = errorMessage( "Problem in uploading file");
  }
?>

Display all uploaded images from MySQL database

To display all the images from the MySQL database as a list. Check this simple script below.

<table class="bordered" style="width:50%; margin:0 auto;">
        <tr>
        	<th width="20%">ID</th>
            <th>IMAGE</th>
        </tr>
		<?php
        $sql = "SELECT * FROM tbl_demo WHERE 1";
        $query = mysql_query($sql);
        while($rs = mysql_fetch_object($query)){ 
        ?>
        <tr>
        	<td align="center" ><?php echo stripslashes($rs->id); ?></td>
            <td align="center"><img src="<?php echo stripslashes($rs->image_url); ?>" alt="" width="100" height="100"> </td>   
        </tr>
        <?php 
		}
		?>
</table>

Give your feedback.comments below.
Share to download the Source Codes for FREE!
We're glad to give free downloads, but we need your love to carry on making that.
Please support us by sharing the page.

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

David Carr on

Looks good, the create table shouldn’t that be called tbl_demo5 to match the rest of the tutorial.

Reply
Nitish Kasar on

Nice script just didn’t got the purpose of preprare_input() what does this function do

Reply
Shahrukh Khan on

i have made a custom function preprare_input() so that it will prevent from sql inejction
you will find this function in common_functions.php under libs folder. Also you can use mysql_real_escape_string() instead to addslashes() too.

function prepare_input($string) {
return trim(addslashes($string));
}

Reply
mayur on

Nice work!

Reply
sanjay on

nice work

Reply
Shahrukh Khan on

thanks

Reply
Suhan Alam Rana on

Great Work

Reply
Shahrukh Khan on

Thank You

Reply
Captain on

Thanks Shahruk. Like you mentioned, the script is for novice….well I happen to be one of them. I got the following errors,

Notice: Undefined index: img_file in C:\xampp\htdocs\learn\gellery\upload.php on line 2

Notice: Undefined variable: ext in C:\xampp\htdocs\learn\gellery\upload.php on line 7

Notice: Undefined index: img_file in C:\xampp\htdocs\learn\gellery\upload.php on line 9

Fatal error: Call to undefined function errorMessage() in C:\xampp\htdocs\learn\gellery\upload.php on line 14

Kindly help me fix them.

I created a table on a database called gallery and created two .php files called index.php and upload.php with the first two main sections respectively

Thanks.

Reply
srinivas on

i am getting the below error for this line

$filePath = $folderName. rand(10000, 990000). ‘_’. time().’.’.$ext;

ERROR:-

Notice: Undefined variable: ext in C:\xampp\htdocs\im

Reply
nisa on

hey i need some help ,
i want to add image. i’m using appery.io, so the interface for the apps are all using appery.io
my problem is i want to add image on registration,from the tutorial u gave have the html form
i’m using this example of code for registration http://itm354.info/assignments/CheckinServices.php.html
how can i upload image in the registration as a default pic? hope you can help me,i really need to know as soon as possible

Reply
Shahrukh Khan on

Havent work on appery.io before please check their official website for help.

Reply
Gurwinder Singh on

hey,use a default path in string,and check if user click on button and file_txt==”” then store default string in backend else store file_ txt

Reply
SANLAP BOSE on

This is a nice script,but we do not see the uploaded image….Please Help..

Reply
Shahrukh Khan on

make sure the image link is properly set.

Reply
nadim on

thanks its very usefull code…

Reply
hitesh on

not able to download files, already like, tweet and used plus

Reply
Shahrukh Khan on

please try once more it will work.

Reply
benson on

Me too can’t download. Any help. the moment i click on download it redirects to https://aarafacademy.com

Shahrukh Khan on

double clicking on the social locker may solve this issue

hitesh on

Call to undefined function prepare_input() in E:\server\data\localweb\project\………….

Reply
Shahrukh Khan on

you must not have called functions folder where this function code is written . you can remove prepare_input() function if you dont want it.

Reply
hitesh on

I removed prepare_input() function though it is not working. Anyway thanks for the reply.

benson on

I am unable to download the files. kindly help. i have liked on Facebook but still can’t download.

Reply
benson on

I am not able to download the files. kindly help. i have liked on Facebook but still can’t download.

Reply
Thaha on

Problem in saving to database

How to solve this error

Reply
cyril on

the ‘$ext’ variable isn’t defined and its what is actually required….

Reply
surya on

sir downloading is working

Reply
ashish on

I have getting following error..
image sucessfully insert and display but at that time i have getting this error msg,
tell me how to solve this issue..

“Strict Standards: Only variables should be passed by reference in C:\xampp\htdocs\personal\upload-image\3\index.php on line 25”

thank you

Reply
Shahrukh Khan on

in your php.ini file turn of strict mode.

Reply
migliori vaporieri on

This article is really a good one it helps new net viewers, who are wishing in favor of blogging.

Reply
Rishi on

Really good work

Reply
pooja on

Nice Work,
insert query is firing on each page refresh once one record is inserted

Reply
asim on

the folder isnt created and only image paths are saved kindly help

Reply
Shahrukh Khan on

folder you can create manually. make sure you have write permission on them.

Reply
Asim on

I have already created a folder..
But it doesnt upload the images. I am working on local Host and have full permission

Shahrukh Khan on

what is your error message?

Subraa PD on

How do I configure this code to upload pdf and .exe file?

Thanks in advance!!

Reply
Shahrukh Khan on

change in mime type.

Reply
Subbu on

Great work!

At the start I had few errors ti fix. now it works just the way I need.

Thanks a TON!

Reply
Shahrukh Khan on

You are welcome

Reply
Bhimaraya Sajjan on

when we reload the page(or refresh), auto-executing inserting mysql query, with same duplicate data

Reply
Shahrukh Khan on

That’s natural, make sure the form is not submitted again, by redirecting the using query parameters.

Reply
situsqq99.com on

Hello Dear, are you truly visiting this web site daily, if so after that you will without doubt take nice experience.

Reply
Joshua Savage on

I am having issue solving this one issue below is the errors i cant seem to figure out at all any help would be appreciated thanks.

Warning: mysqli_query() expects at least 2 parameters, 1 given in C:xampphtdocsuploadindex.php on line 126

Warning: mysqli_fetch_object() expects parameter 1 to be mysqli_result, null given in C:xampphtdocsuploadindex.php on line 127

Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.