Welcome To baselogics.blogspot.in

Welcome to baselogics.blogspot.com

Place to Learn Programmes.

Bits and Bytes....

Computer Scientists Love Their Algorithms and Data Structures

Explore all new Mathematical Puzzles......

Jasper Roberts - Blog

Tuesday, July 7, 2015

Converting JPEG/image type files into BLOB (binary large object) and saving them into MySQL Database...............

                       While Creating Secured Login system or Secure Systems , we need to put data into MySQL Database. Unlike, Uploading it on server and Saving its address into Database can be dangerous. it can be accessed easily by the Person who is not expected to see it. thats why web developers store them into database in binary format and retrieve whenever needed.
Here's Short Tutorial On Storing JPEG/image files on MySQL in BLOB (actually .bin) format.

1. Eshtablishing connection to MySQL Server    


Code for Connection to database(file name ='connect_db.php')


<?php
       $mysql_host = 'localhost';
       $mysql_db ='practice';
       $mysql_username ='root';
       $mysql_pass = ' ';

       $connect_server = mysql_connect($mysql_host,$mysql_username,$mysql_pass) or die();
       mysql_select_db($mysql_db) or die('Error :could not connect');
?>

In Above Code Replace localhost,practice ,root ,etc. with your database name, username, password and hostname.We will going to require this file in each page where we need to access database.


2.Create Form Page Or File Submit Page Where You Can Convert,Insert That Image Into MySQL

Code For Page Where You Actually Taking Image And Saving it (file name='form.php' )



<form method="POST" enctype="multipart/form-data">
        <input type="file" name="image">
<input type="submit" name="submit">
 </form>

<?php
        require 'connect_db.php';
        if(isset($_POST['submit'])&&(!empty($_FILES['image']['tmp_name'])))
        {
             $pic_data = addslashes(file_get_contents($_FILES['image']['tmp_name']));
             $pic_size=$_FILES['image']['size'];
             $query="INSERT INTO `pic-table`      VALUES('','{$pic_data}','{$pic_size['mime']}')";
             mysql_query($query) or die('ERROR: Failed');
         }
        else
       {
             echo 'Please Submit File';
        }
?>



MySQL Database Details
Database Name= 'practice'
Table Name= 'pic-table'
Columns=1.id(int)NOT NULL AUTO_INCREMENT
                 2.pic-data(BLOB)NOT NULL
                 3.pic-size(int)NOT NULL