How to upload image in database using PHP MySQL?

In this tutorial you will learn how to insert or upload image in MySQL database in very easy way. Here I will explain each and everything in step by step so that you can understand easily.

Here I am using mysql database for storing the image and Php code for insert or upload the image.

Note: - In this tutorial we are only storing the image path or image name in database but actual image we are storing in folder.

What we are doing in this tutorial?

Step 1.

First we will create an upload design page in Php so that we can upload our images to database. Now create an upload design page in Php like below design. My Php upload design page name is upload-design.php.

PHP Upload Image in Database

Copy the below complete HTML code and paste it in upload-design.php page.

	
	<html>
	<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, intial-scale=1.0"/>
	<title>Image Upload - Campuslife</title>
	<style>
	
		html, body{background: #ececec; height: 100%; margin: 0; font-family: Arial;}
		.main{height: 100%; display: flex; justify-content: center;}
		.main .image-box{width:300px; margin-top: 30px;}
		.main h2{text-align: center; color: #4D4D4D;}
		.main .tb{width: 100%; height: 40px; margin-bottom: 5px; padding-left: 5px;}
		.main .file_input{margin-top: 10px; margin-bottom: 10px;}
		.main .btn{width: 100%; height: 40px; border: none; border-radius: 3px; background: #27a465; color: #f7f7f7;}
		.main .msg{color: red; text-align: center;}
	
	</style>
	</head>

	<body>
	<!-------------------Main Content------------------------------>
	<div class="container main" >
		<div class="image-box">
			<h2>Image Upload</h2>
			<form method="POST" name="upfrm" action="" enctype="multipart/form-data">
				<div>
					<input type="text" placeholder="Enter image name" name="img-name" class="tb" />
					<input type="file" name="fileImg" class="file_input" />
					<input type="submit" value="Upload" name="btn_upload" class="btn" />
				</div>
			</form>
			<div class="msg">

			</div>
		</div>
	</div>
	</body>
	</html>
	

Now our designing part has been completed and now we will follow the step 2.

Step 2.

Now create an image folder so that image will be save or store in folder and image path will we save in database. We will use this folder in our php code.

So create a folder with photo name where you will deploy your application.

Php image folder

Step 3.

After creating the image folder now we will create database and table structure. Here I am creating database with name campuslife. Below is the command of creating the database.


	create database campuslife
	

Now we will use this database so that we can create table inside this campuslife database. Below is the command to use the campuslife database.


	use campuslife

Now we are inside the campuslife database and we will create a table in this database with image_table name. Here I am creating a table with 3 field name, like img_id, img_name, img_path.

The image id will generate automatically when we insert the image in table. In mysql we will set img_id (auto_increment), so that whenever we will insert image in table a unique id will generate automatic for every new image. For creating a table follow the below command.

	
	create table image_table
	(
		img_id int auto_increment,
		img_name varchar(50),
		img_path varchar(100),
		primary key(img_id)
	)
	

img_id: column for generating the automatic unique id for every image.

img_name: column for storing the image name.

img_path: column for storing the image path with folder name.

Why we are creating id for image?

Because we will use img_id for delete the image.

Step 4.

I am creating separate connection file so that I can access it anywhere in page. Now create a connection.php file. In this we will add connection information of MySQL so that we can create connection between PHP to MySQL for login.

Why separate connection file?

Because we can call that file in many pages. If we can’t create separate file for connection then we have to write same code in every pages manually. It is good for single or two pages, but not good for 10 or more pages.

Connection file contain below information like (host name, MySQL user name, MySQL password, database name). Change the connection information as your MySQL login information in connection.php file.

Copy the below code and paste it in connection.php page.


	<?php

	$host ="localhost";
	$uname = "root";
	$pwd = '123456';
	$db_name = "campuslife";

        ?>
	

Step 5.

Now create an image upload Php page to perform the insertion operation to upload the image in table. In Php we will use MySQL insert query to insert the image in database. My php page name is upload-code.php.

Copy the below complete Php code and paste it in upload-code.php page.


<?php

	/*-- we included connection files--*/
	include "connection.php";

	/*--- we created a variables to display the error message on design page ------*/
	$error = "";

	if (isset($_POST["btn_upload"]) == "Upload")
	{
		$file_tmp = $_FILES["fileImg"]["tmp_name"];
		$file_name = $_FILES["fileImg"]["name"];

		/*image name variable that you will insert in database ---*/
		$image_name = $_POST["img-name"];

		//image directory where actual image will be store
		$file_path = "photo/".$file_name;	

	/*---------------- php textbox validation checking ------------------*/
	if($image_name == "")
	{
		$error = "Please enter Image name.";
	}

	/*-------- now insertion of image section has start -------------*/
	else
	{
		if(file_exists($file_path))
		{
			$error = "Sorry,The <b>".$file_name."</b> image already exist.";
		}
			else
			{
				$result = mysqli_connect($host, $uname, $pwd) or die("Connection error: ". mysqli_error());
				mysqli_select_db($result, $db_name) or die("Could not Connect to Database: ". mysqli_error());
				mysqli_query($result,"INSERT INTO image_table(img_name,img_path)
				VALUES('$image_name','$file_path')") or die ("image not inserted". mysqli_error());
				move_uploaded_file($file_tmp,$file_path);
				$error = "<p align=center>File ".$_FILES["fileImg"]["name"].""."<br />Image saved into Table.";
			}
		}
	}
?>

Step 6.

Now add upload-code.php page in upload-design.php page at the top like below. Just copy the below code and paste it in your upload-design.php page at the top.

	
	<?php
	
		include('upload-code.php'); // Include upload code Script page.
		
	?>
	
PHP include function

Step 7.

Now we will show Php success or error message on design. Whether image inserted or saved in database or not. So copy the below Php code and paste it in upload-design.php page in <div class="msg"> ... </div> tag.

	
	<strong>
		<?php if(isset($error)){echo $error;}?>
	</strong>
	
	
	<div class="msg">
		php success or error mesage will come here...
	</div>
	

Step 8. Final Step

Now our task has been completed and now test your tutorial on browser. As we know our php tutorial run on local server. So test your application on localhost. Run the upload-design.php page and test your tutorial.

I hope you liked this tutorial. If you found any mistake or error this tutorial then please let me know through contact us or feedback page or you can post comment here.

Watch Tutorial Video

Post Your Comment