How we can upload images to MySQL database using Php

A Php script to upload images to Mysql Database upload


images in Mysql using PhpHi readers today we came up with the topic of upload images in the database using MySQL procedural functions and PHP. Upload an image is just like inserting records in the database but in binary format. Here we have provided the step-by-step guide with a simple example with full source code in a readable format.So no need to worry!.here we start a topic how to upload images in MySql database using PHP MySQL code

create a database in localhost/PHPMyAdmin

create a database with a name imageupload and execute the below script to create table images.

 

CREATE TABLE IF NOT EXISTS `images` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`name` varchar(100) DEFAULT NULL,

`size` int(11) DEFAULT NULL,

`type` varchar(20) DEFAULT NULL,

`content` mediumblob NOT NULL,

PRIMARY KEY (`id`)

) ;

Step::1 create an Html form

First, create the Html file and copy the below code and then save it.

upload.html
<!Doctype html>
<html>
 <head>
 <title>Upload images to mysql database.</title>
 <style type="text/css">
 img{
 margin: .2em;
 border: 1px solid #555;
 padding: .2em;
 vertical-align: top;
 }
 </style>
 </head>
 <body>
 
 <form action="upload.php" method="post" enctype="multipart/form-data" >
 <div>
 <h3>Image Upload:</h3>
 </div>
 <div>
 <label>Image</label>
 <input type="hidden" name="MAX_FILE_SIZE" value="500000">
 <input type="file" name="image" />
 <input name="submit" type="submit" value="Upload" value="Submit">
 </div>
 </form>
 </body>
</html>

Three things must be noted in above html form:

      1.  enctype   :  enctype is a form attribute which is used to specify how the form-data is to be encoded when the form has been submitted to the server.

 Here we have use enctype value =”multipart/form-data” in order to use the file upload control in form to upload images.

      Note: enctype attribute is used only if form is submitted using “POST” method.

     2.  input type=”hidden”: This input type is generally used to hide the field i.e. hidden field is not visible to the user for security measures.One thing should be noted here that the input type =”hidden” must have default value using value attribute.

     3.  input type=”file”: This input type is used to select files. This will provide the browse button to choose a file to upload.


Step:2 Create the PHP script file to upload images

In the second step create the upload.php file and copy the below code and then save it.

In this PHP file first we have checked the form has been submitted by post method and $_FILES is non-empty then store the various attributes of $_FILES in a variable. Then perform some check condition to impose a restriction on selected files like:

1 )  Limit the file type selected:      Here we have imposed a restriction on the type of file to select only png, x-png, jpeg, pipe, gif files using    in_array() function of PHP.

//check file extension

if ($formOk && !in_array($type, array('image/png', 'image/x-png', 'image/jpeg', 'image/pjpeg', 'image/gif'))) 
{
 $formOk = false;
 echo "Error: Unsupported file extension. Supported extensions are JPG / PNG.";
 }

2 ) Limit the file size: Here we have imposed a restriction on the size of the file to be uploaded by using filesize($path) function of PHP.

 // check for file size.

 if ($formOk && filesize($path) > 500000) {
 $formOk = false;
 echo "Error: File size must be less than 500 KB.";
 }

Finally, after imposing restriction we have used the MySQL procedural function to connect to the database and insert the chosen file in binary format in BLOB type field “content” then check if any error show error message otherwise show “file has successfully uploaded” message then use the mysqli_close(link) to close the connection.


Full source code of “upload.php” file
<?php
/* Upload an image to mysql database.*/

// Check for post data.
if ($_POST && !empty($_FILES)) {
 $formOk = true;

//Assign Variables
 $path = $_FILES['image']['tmp_name'];
 $name = $_FILES['image']['name'];
 $size = $_FILES['image']['size'];
 $type = $_FILES['image']['type'];

if ($_FILES['image']['error'] || !is_uploaded_file($path)) {
 $formOk = false;
 echo "Error: Error in uploading file. Please try again.";
 }

//check file extension
 if ($formOk && !in_array($type, array('image/png', 'image/x-png', 'image/jpeg', 'image/pjpeg', 'image/gif'))) {
 $formOk = false;
 echo "Error: Unsupported file extension. Supported extensions are JPG / PNG.";
 }
 // check for file size.
 if ($formOk && filesize($path) > 500000) {
 $formOk = false;
 echo "Error: File size must be less than 500 KB.";
 }

if ($formOk) {
 // read file contents
 $content = file_get_contents($path);

//connect to mysql database
 if ($conn = mysqli_connect('localhost', 'root', '', 'imageupload')) {
 $content = mysqli_real_escape_string($conn, $content);
 $sql = "insert into images (name, size, type, content) values ('{$name}', '{$size}', '{$type}', '{$content}')";

if (mysqli_query($conn, $sql)) {
 $uploadOk = true;
 $imageId = mysqli_insert_id($conn);
 echo "image is successfully uploaded";
 } else {
 echo "Error: Could not save the data to mysql database. Please try again.";
 }

mysqli_close($conn);
 }

 else {
 echo "Error: Could not connect to mysql database. Please try again."; }
 }
}
?>

Snapshot View of upload images in MySQL:

upload images
upload images

 



I hope you would like this tutorial on how we can upload images in MySQL using PHP script!

Read next article to display images

Leave a Comment