In this tutorial we will learning to upload, store and fetch image from MySql Database. For that we will create a simple form to upload a image. Now the user will use this form to upload the image. Php will grab the submitted image and save it in a specific directory. Also it’s name and the link pointing to the directory will be saved on database.

Step 1: Create a Database

The first step in this tutorial is the creation of a MySQL database. Create a database with the name uploadImage using the following SQL query.

CREATE DATABASE uploadImage;

STEP 2: CREATE A TABLE IN MYSQL.

The second step in this tutorial is the creation of a MySQL table. Create a table image in database using the following SQL query.

CREATE TABLE IF NOT EXISTS `image` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `path` varchar(500) DEFAULT NULL,
  `name` varchar(500) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
COMMIT;

STEP 3: CREATE A MYSQL CONNECTION

Create a separate file dbconnect.php to handle the database connection. Add the following code and replace the database credentials with yours. You can find your db credentials in Application Access details:

<?php

$dbHost = 'localhost' ;
$dbUser = 'root' ;
$dbPass = '' ;
$dbName = 'uploadImage' ;
$con = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName) ;
if(!$con){
    die("Database Connection Failed: " . mysqli_connect_error());
}
?>

Step 4: Image Upload Form

In this section we will create a form in our index.php file. And this form will be used for uploading the image.

<form method="POST" action="getdata.php" enctype="multipart/form-data">
		<input type="file" name="myimage">
		<input type="submit" name="submit_image" value="Upload">
	</form>

Step 5: Storing Image

In this section we will store the image on the specific directory. Also we will save the image name and link to the database.

$uploads_dir="/wamp64/www/uploadImage/images/";

if( $_FILES["myimage"]["size"] < 2101547 ){
	$tmp_name = $_FILES["myimage"]["tmp_name"];

	// basename() may prevent filesystem traversal attacks;
	$name = basename($_FILES["myimage"]["name"]);
	
	move_uploaded_file($tmp_name, "$uploads_dir/$name");

	$sql="INSERT INTO image (path, name) VALUES('/uploadImage/images/','$name')";

	$var=mysqli_query($con, $sql);

	if($var){
		echo "File uploaded successfully.";
	}else{
		echo "Oops ! Some problem occured. Please try again later.";
	}

}else{
	echo "File size is greater than the estimated size.";
}

Step 6: Fetching Image

Here we will show all the uploaded image in a table. For this we will use the image name and link that we have saved in our database. The link will redirect us to the folder where image is saved. While image name will help us to select or pick up the image from that folder.

<?php 

include('dbconnect.php');
 
$result = mysqli_query($con, "SELECT * FROM image "); 
echo "<table border='1' width='auto' cellspacing='0' >"; 
        echo "<tr>";
            echo "<td><strong>Name</strong></td>";
            echo "<td><strong>Image</strong></td>";
        echo "</tr>";
    while($row = mysqli_fetch_array($result)) { 
        echo "<tr>";
        echo "<td>" . $row['name'] . "</td>";
        echo "<td><img src='".$row['path']."/".$row['name']."' alt='".$row['name']."' width='100' height='100'></td>";
        echo "</tr>"; 
    }
echo "</table>";
mysqli_close($con);
?>

To view the image you should go to the fetch_image.php

CONCLUSION

In this article, we discussed how we can upload, store and fetch image in MySql database using PHP. This is a simple example you can add more complex logic and validations as per your requirements. If you wish to add to the discussion or would like to ask a question, leave a comment below.

Comments

  1. hello!,I love your writing so so much! proportion we keep up a correspondence extra about your post on AOL?
    I require a specialist on this area to solve my problem.
    May be that’s you! Taking a look ahead to look you.

  2. hello there and thank you for your info – I have definitely picked up anything new from right here. I did however expertise a few technical issues using this web site, as I experienced to reload the web site many times previous to I could get it to load correctly. I had been wondering if your web host is OK? Not that I’m complaining, but slow loading instances times will sometimes affect your placement in google and could damage your quality score if ads and marketing with Adwords. Anyway I’m adding this RSS to my e-mail and could look out for much more of your respective interesting content. Make sure you update this again very soon..

  3. Wow! This blog looks just like my old one! It’s on a totally different topic but it has pretty much the same layout
    and design. Wonderful choice of colors!

Leave a Reply

Your email address will not be published. Required fields are marked *