Thursday 20 October 2016

Insert and Fetch Images From Mysql Database in PHP





In this post we are going to discuss how can we store images into mysql database table and display that store image from mysql table to web page by using php script. If you have trying to store uploaded images into mysql table and if you have facing problem while inserting images into table then you can find solution of this things here. Here we will store uploaded images into mysql table and after this we will display that stored mysql image on web page by using php script. In mysql table images will be stored into binary form of data. We will use mysql blob data type in mysql table and in this datatype we have store images in binary form. Here we have define one input file element and one submit button we can select file from this input element and click on submit button then after image will be send to php script and by using file_get_contents() function we can read selected image file in string format and after this we will insert that image into mysql database. In mysql database table we have store image in column with data type blob. After this we want to display image on web page so we have show that inserted image into image tag by converting binary data into image by using base64encode() function. So this way we can insert image into mysql database by using php script.




Source Code


tbl_images


 --  
 -- Table structure for table `tbl_images`  
 --  
 CREATE TABLE IF NOT EXISTS `tbl_images` (  
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `name` blob NOT NULL,  
  PRIMARY KEY (`id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;  

index.php


 <?php  
 $connect = mysqli_connect("localhost", "root", "", "testing");  
 if(isset($_POST["insert"]))  
 {  
      $file = addslashes(file_get_contents($_FILES["image"]["tmp_name"]));  
      $query = "INSERT INTO tbl_images(name) VALUES ('$file')";  
      if(mysqli_query($connect, $query))  
      {  
           echo '<script>alert("Image Inserted into Database")</script>';  
      }  
 }  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Insert and Display Images From Mysql Database in PHP</title>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
      </head>  
      <body>  
           <br /><br />  
           <div class="container" style="width:500px;">  
                <h3 align="center">Insert and Display Images From Mysql Database in PHP</h3>  
                <br />  
                <form method="post" enctype="multipart/form-data">  
                     <input type="file" name="image" id="image" />  
                     <br />  
                     <input type="submit" name="insert" id="insert" value="Insert" class="btn btn-info" />  
                </form>  
                <br />  
                <br />  
                <table class="table table-bordered">  
                     <tr>  
                          <th>Image</th>  
                     </tr>  
                <?php  
                $query = "SELECT * FROM tbl_images ORDER BY id DESC";  
                $result = mysqli_query($connect, $query);  
                while($row = mysqli_fetch_array($result))  
                {  
                     echo '  
                          <tr>  
                               <td>  
                                    <img src="data:image/jpeg;base64,'.base64_encode($row['name'] ).'" height="200" width="200" class="img-thumnail" />  
                               </td>  
                          </tr>  
                     ';  
                }  
                ?>  
                </table>  
           </div>  
      </body>  
 </html>  
 <script>  
 $(document).ready(function(){  
      $('#insert').click(function(){  
           var image_name = $('#image').val();  
           if(image_name == '')  
           {  
                alert("Please Select Image");  
                return false;  
           }  
           else  
           {  
                var extension = $('#image').val().split('.').pop().toLowerCase();  
                if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)  
                {  
                     alert('Invalid Image File');  
                     $('#image').val('');  
                     return false;  
                }  
           }  
      });  
 });  
 </script>  

43 comments:

  1. Hello sir, first of all thank you for this script. I loved all your videos. Great videos i ever saw, clean explanation of the code.. Looking for some some stuffs like this.. My question here is, once i upload images using above scripts, only the half portion of the images are displayed, Why so?? Thank you

    ReplyDelete
    Replies
    1. hello here in your data base you are using blob type just change it with longblob and then you will be able to add 16mb file or image in it.

      Delete
    2. Hello, you should change img tag height or width for that problem..!!

      Delete
    3. Change blob to longblob in the mysql query script.

      Delete
    4. thx sir, i also had same problem

      Delete
    5. can we use multiple blobs in table ?...if not then solution pls...

      Delete
  2. Hi,I am unfortunately getting this error.Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\work\index.php on line 41.Any idea what it means please? Still on the learning curve of php sorry....
    here is my code with databse testing table name tbl_image.

    ReplyDelete
  3. Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\work\index.php on line 40
    Im getting this error pls explain

    ReplyDelete
  4. hello sir, everything is ok but when i output the image it just show as a broken image, what can i do

    ReplyDelete
  5. Thank you sir, It's working very well ...!!

    ReplyDelete
  6. Greeting, I am happy and lucky to see this script. I ask if there any other script which shows how to retrieve text from the database file, together with MPEG/audio file and display both of them on the same page. ( it looks like one speak what he read from display text page. Waiting for your reply.
    Best regards

    ReplyDelete
  7. Can you please make a video or suggested CRUD application by using Bootstrap and insert,edit,view and delete using Bootstrap modal. Request by Mustafizur

    ReplyDelete
  8. Sir, Thanks for this great code. But needed some help. When I upload an image, I want that particular image to be displayed but not all the other images in the database. Need help in this one. Thanks in advance.

    ReplyDelete
    Replies
    1. $query = "SELECT * FROM tbl_images ORDER BY id desc limit 1";

      Delete
  9. cant create blob into database why so

    ReplyDelete
  10. Good. Your code is simple and easy.No any time lost.

    ReplyDelete
  11. Thaks alot.How to give thank to YOU.I don't know.May Allah bless you.YOU ARE GREAT!!!!.I have seen many videos but not to able to get gool.Many people giving videos but chitting with viewers.I am greatful to you.From deep of my heart I will bless for you.Again I am writting .May allah bless you.Long live.

    ReplyDelete
  12. Thank you very much sir,
    I had a problem. While display the image in the browser only half of the image is displayed. Can you help me to bring full image and which place i made mistake..

    ReplyDelete
  13. how i convert a image filename to image itself when displaying values from database

    ReplyDelete
  14. thanks for sharing use full knowledge, respect from pakistan

    ReplyDelete
  15. Sir, Thanks for this great code. But needed some help. When I upload an image, I want that particular image to be displayed but not all the other images in the database. Need help in this one. Thanks in advance.

    ReplyDelete
  16. thank you so much

    ReplyDelete
  17. hey guys. When I click the insert button after choosing a file no file is uploaded. please can somebody help me out

    ReplyDelete
  18. pdo better than mysqli_connect

    ReplyDelete
  19. Sir, after adding an image if page is refreshed, last image is inserted again. Is there solution of the problem.

    ReplyDelete
  20. sir, im getting a error stating data too long for column name can u help me please
    thanks in advance

    ReplyDelete
  21. How to set the secret key for the image using PHP and MySQL

    ReplyDelete
  22. I need to add the text as well right next to the image

    ReplyDelete
  23. image retrive from database is broken

    ReplyDelete
  24. when i am adding more columns to it,i am unable to insert the image.
    can anyone pls help me

    ReplyDelete
  25. HI
    According to what was mentioned in the video, the codes were literally applied, but the picture did not appear for me and I do not know what the problem is. Please help in solving the problem with appreciation

    ReplyDelete
  26. According to what was mentioned in the video, the codes were literally applied, but the picture did not appear for me and I do not know what the problem is. Please help in solving the problem with appreciation

    ReplyDelete