So you are thinking how to upload images to your MySQL database? Here is the Upload Image PHP MySQL Tutorial, and in this tutorial, I am going to explain how we can upload or store images to MySQL database and then how we can retrieve the saved images.
Table of Contents
What We Need?
In this post I will be using.
- Xampp Server
- Sublime Text
You can use other tools as well like wamp, lamp, and notepad++ or any IDE as well. The tools don’t matter the point is we will be using PHP and MySQL. So let’s begin.
Upload Image PHP MySQL Tutorial
Creating Database
- Here I will be storing the image directly to MySQL table. So the first thing we need is our table. And for creating the table you need to go to your PhpMyAdmin.
- Start XAMPP server and go to localhost/phpmyadmin. Here you need to create a database. I have created a database named SimplifiedCoding.
- Now inside this database we need a table as below.
- For creating the above table you can use the following SQL.
1 2 3 4 5 6 7 |
CREATE TABLE `images` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `description` varchar(1000) NOT NULL, `image` longblob NOT NULL ); |
Creating a PHP Project
For this part, you can use any IDE (e.g., PHP Storm, NetBeans, Eclipse, etc.) but here I am using Sublime Text. I would recommend using PHP Storm as I love this IDE but at the same time if you are a beginner then avoid using an IDE to learn better.
- Go to the root directory. For XAMPP it is (c:/xampp/htdocs).
- Here create a folder named ImageUploadProject. (Though you can give it any name it doesn’t matter).
Defining Constants
- Now inside your project first create a php file named Constants.php. This file defines all the constants that are required for our project.
1 2 3 4 5 6 7 8 9 10 |
<?php define("DB_HOST", "localhost"); define("DB_NAME", "simplifiedcoding"); define("DB_USER", "root"); define("DB_PASS", "password"); define("MAX_SIZE_ALLOWED", 1048576); //around 1mb |
Connecting to Database
- Now we will create a php class named DbConnect to connect to our Database. So create a new file named DbConnect.php and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?php class DbConnect{ private $con; public function __construct(){ } public function connect(){ //getting the constants from the file require_once dirname(__FILE__). '/Constants.php'; //connecting to database $this->con = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); //if there is an error //return null if(mysqli_connect_errno()){ echo 'Failed to connect with database'. mysqli_connect_error(); return null; } //if everything goes well return the connection return $this->con; } } |
Class to Perform Store and Retrieve Operation
- After database connection we need to perform the store and retrieve operation. So lets create a new class named StoreImage inside a new file named StoreImage.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
<?php class StoreImage{ private $con; public function __construct(){ //getting the connection file require_once dirname(__FILE__) . '/DbConnect.php'; //creating the object of the dbconnect class $db = new DbConnect; //getting the connection $this->con = $db->connect(); } //the method will save the image to database public function saveImage($desc, $image){ $stmt = $this->con->prepare("INSERT INTO images (description, image) VALUES (?, ?)"); $stmt->bind_param("ss", $desc, $image); if($stmt->execute()) return true; return false; } //the method will return all the images from the database //excluding the image, we will create a separate method for getting the image content //as the image is stored in string format we need to fetch it separately public function getAllImages(){ $stmt = $this->con->prepare("SELECT id, description FROM images ORDER BY id DESC"); $stmt->execute(); $stmt->bind_result($id,$desc); $images = array(); while($stmt->fetch()){ array_push($images, array('id'=>$id, 'desc' => $desc)); } $stmt->close(); return $images; } //this method will return the actual image content public function getImageContent($imageid){ $stmt = $this->con->prepare("SELECT image FROM images WHERE id = ?"); $stmt->bind_param("i", $imageid); $stmt->execute(); $stmt->bind_result($image); $stmt->fetch(); return $image; } } |
Converting String to Image
- We have stored the image as the String. But we can’t display the string to the user, we need to display it as an image. So for this we will create one more file where we will pass the image id and it will give us the image in image format.
- So create a new file named image.php and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php if(isset($_GET['id'])){ require_once dirname(__FILE__) . '/StoreImage.php'; $storeimage = new StoreImage; header('content-type: image/jpeg'); echo $storeimage->getImageContent($_GET['id']); }else{ header('Location: image-upload.php'); } |
Uploading and Retrieving Images
- Now here is our final operation. Create a file named image-upload.php and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
<!DOCTYPE html> <?php require_once dirname(__FILE__) . '/StoreImage.php'; ?> <html> <head> <title>Upload Image PHP MySQL Tutorial</title> <link rel='stylesheet' href='style.css' /> </head> <body> <header> <h1>Upload Image PHP MySQL Tutorial</h1> <h2>www.simplifiedcoding.net</h2> </header> <?php $uploaded = ""; if($_SERVER['REQUEST_METHOD'] == 'POST'){ $storeimage = new StoreImage; $desc = $_POST['desc']; $image = $_FILES['image']['tmp_name']; if(!($_FILES['image']['size'] > MAX_SIZE_ALLOWED)){ $imagecontent = file_get_contents($image); if($storeimage->saveImage($desc, $imagecontent)){ $uploaded = 'Image successfully uploaded'; }else{ $uploaded = 'Some error occurred please try again'; } }else{ $uploaded = 'File exceeds the maximum size limit'; } } ?> <content> <div class='uploadpanel'> <form method="POST" enctype="multipart/form-data"> <div> <input type='text' name='desc' placeholder="enter image description" required /> </div> <div> <input type='file' name='image' accept="image/*" required /> </div> <div> <button>Save Image</button> </div> </form> <?php echo !empty($uploaded)?"<div class='alert'><p>$uploaded</p></div>":""; ?> </div> <div class='imagespanel'> <h2>Uploaded Images</h2> <?php $storeimage = new StoreImage; $images = $storeimage->getAllImages(); foreach($images as $image){ ?> <div class='image' style="float: left; width:100%; height:100%; text-align: center"> <p> <image width='250' height='auto' src='<?php echo "http://localhost/ImageUploadProject/image.php?id=".$image['id']?>' /> </p> <p> <?php echo $image['desc']; ?> </p> </div> <?php } ?> </div> </content> <footer> <p> Copyright © 2017 <a href='https://www.simplifiedcoding.net'>Simplified Coding</a></p> </footer> </body> </html> |
- Now you can test your project.
- Bingo! It is working absolutely fine. Additionally you can apply CSS to make it look awesome.
Applying CSS to the Project
- Create a file named style.css and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
body{ margin:0; padding:0; font-family: arial; } h1,h2{ margin:0; } header{ padding:1% 0 1% 0; color:#cdd2d4; text-align: center; width:100%; height:80px; background-color:#2c849e; } a{ color:#cdd2d4; text-decoration: none; } a:hover{ color: #02415a; } footer{ float:left; margin:5% 0 0 0; padding:1% 0 1% 0; color:#cdd2d4; text-align: center; width:100%; height:30px; background-color:#2c849e; } content{ height:600px; width:100%; padding:5px; } .uploadpanel{ float:left; width:60%; text-align: center; } .uploadpanel div{ margin:2%; } .imagespanel{ text-align: center; width:30%; float:left; max-height:400px; overflow-y: scroll; } button{ color:#cdd2d4; border:none; border-radius: 10px; width:200px; height:40px; background-color:#02415a; } button:hover{ cursor: pointer; background-color: #106688 } input{ font-size: 16px; width:300px; height:45px; } |
- Now you will see the project like this.
Upload Image PHP MySQL Source Code
- If you are having any problem you can also get my source code from the below given link.
[sociallocker id=1372] Upload Image PHP MySQL Source Code [/sociallocker]
So that’s all for this Upload Image PHP MySQL Tutorial guys. If you found this post useful, then please SHARE it. And if having any queries or question, then just comment it below. Thank You 🙂