x10Hosting Forums

Corporate Free Hosting for the Masses.



Register

Reply
 
LinkBack Thread Tools Display Modes
x10Hosting Member

Join Date: Jun 2008
Posts: 7
Credits: 401
tstivers is on a distinguished road
Quote  
07-17-2008, 06:36 AM
How to store images in a MySQL database

i'm bored, and this seems like some nice information, so i'm going to write a tutorial for it... i learned how to do this from phpriot.com, but the tutorial is in my own words, not copied/pasted from their site

How to store/retrieve images in a MySQL database:

First off, the images are going to be stored in what is called a BLOB column

Q: What is a BLOB column?
A: A Binary Large Object, basically, it's used to store binary data in a MySQL database

Creating the image table:

You must create a table to store the images in.
Create a table named Images (or whatever you like) with 6 columns

Name the first column Image_ID with type tinyint and a length of 3, this should be an auto-incremented column

Name the second column Image_Type with type varchar and length of 25, we'll use this to store the mime type

Name the third column Image with type blob, this is where we will store the actual image

Name the fourth column Image_Size with type varchar and length of 25, this will tell us the size of the image

Name the fifth column Image_Category with type varchar and length of 25, this will be used to categorize the images

Name the sixth column Image_Name with type varchar and length of 50, if you havn't guessed, this will be the name of our image

the following code *should* create the table for you, although i havn't tested it
PHP Code:
create table Images (
    
Image_ID        tinyint(3)  not null default '0',
    
Image_Type      varchar(25not null default '',
    
Image           blob        not null,
    
Image_Size      varchar(25not null default '',
    
Image_Category  varchar(25not null default '',
    
Image_Name      varchar(50not null default ''
); 
Next we need the upload form

ok, i lied, the following is a direct copy/paste from phpriot

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html>
    <head><title>File Upload To Database</title></head>
    <body>
        <h3>Please Choose a File and click Submit</h3>
 
        <form enctype="multipart/form-data" action="upload_image2.php" method="post">
            <input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
            <input name="userfile[]" type="file" />
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>
this is just a basic form, put it in a .php file (we'll name it upload_image.php for this tutorial)

Create the uploader

Now we have to create the php script that does the actual uploading, this is another direct copy/paste from phpriot

PHP Code:
<?php
    
// check if a file was submitted
    
if(!isset($_FILES['userfile'])) {
        echo 
'<p>Please select a file</p>';
    }
    else
        {
        try {
            
upload();
            
// give praise and thanks to the php gods
            
echo '<p>Thank you for submitting</p>';
        }
        catch(
Exception $e) {
            echo 
$e->getMessage();
            echo 
'Sorry, could not upload file';
        }
    }
?>
don't run this script yet as there isn't an upload function created
as of yet, for now, just put it in a file (we'll name the file upload_image2.php for this tutorial)

basically, what this does, is check that the user actually entered a file, if so, it attempts to upload the image
if there is an error, it will return the error and abort

next we need to create the upload function

following is another copy/paste from phpriot

PHP Code:
<?php
    
// the upload function
    
function upload(){
 
    if(
is_uploaded_file($_FILES['userfile']['tmp_name'])) {
 
        
// check the file is less than the maximum file size
        
if($_FILES['userfile']['size'] < $maxsize)
            {
        
// prepare the image for insertion
        
$imgData =addslashes (file_get_contents($_FILES['userfile']['tmp_name']));
        
// $imgData = addslashes($_FILES['userfile']);
 
        // get the image info..
          
$size getimagesize($_FILES['userfile']['tmp_name']);
 
        
// put the image in the db...
          // database connection
          
mysql_connect("localhost""$username""$password") OR DIE (mysql_error());
 
          
// select the db
          
mysql_select_db ("$dbname") OR DIE ("Unable to select db".mysql_error());
 
        
// our sql query
        
$sql "INSERT INTO Images
                ( Image_ID , Image_Type ,Image, Image_Size, Image_Name)
                VALUES
                ('', '{$size['mime']}', '{$imgData}', '{$size[3]}', '{$_FILES['userfile']['name']}')"
;
 
        
// insert the image
        
if(!mysql_query($sql)) {
            echo 
'Unable to upload file';
            }
        }
    }
    else {
         
// if the file is not less than the maximum allowed, print an error
         
echo
          
'<div>File exceeds the Maximum File limit</div>
          <div>Maximum File limit is '
.$maxsize.'</div>
          <div>File '
.$_FILES['userfile']['name'].' is '.$_FILES['userfile']['size'].' bytes</div>
          <hr />'
;
         }
    }
?>
put this at the top of the upload_image2.php file

what this does:

1. check if the file is an allowed type
2. make sure the uploaded file isn't bigger than the max file size
3. format the binary data for insertion into the database
4. connect to the database
5. insert the data

now we must display the image

another copy/paste from phpriot

PHP Code:
<?php
    
// just so we know it is broken
    
error_reporting(E_ALL);
    
// some basic sanity checks
    
if(isset($_GET['Image_ID']) && is_numeric($_GET['Image_ID'])) {
        
//connect to the db
        
$link mysql_connect("localhost""username""password") or die("Could not connect: " mysql_error());
 
        
// select our database
        
mysql_select_db("Images") or die(mysql_error());
 
        
// get the image from the db
        
$sql "SELECT Image FROM Images WHERE Image_ID=0";
 
        
// the result of the query
        
$result mysql_query("$sql") or die("Invalid query: " mysql_error());
 
        
// set the header for the image
        
header("Content-type: image/jpeg");
        echo 
mysql_result($result0);
 
        
// close the db link
        
mysql_close($link);
    }
    else {
        echo 
'Please use a real id number';
    }
?>
put this in a file named get_image.php

Displaying the image and related information

another copy/paste

PHP Code:
<?php
    
// again we check the $_GET variable
    
if(isset($_GET['Image_ID']) && is_numeric($_GET['Image_ID'])) {
        
$sql "SELECT Image_Type, Image_Size, Image_Name FROM Images WHERE Image_ID=".$_GET['Image_ID'];
 
        
$link mysql_connect("localhost""username""password") or die("Could not connect: " mysql_error());
 
        
// select our database
        
mysql_select_db("Images") or die(mysql_error());
 
        
$result mysql_query($sql)  or die("Invalid query: " mysql_error());
 
        while(
$row=mysql_fetch_array($result)) {
            echo 
'This is '.$row['Image_Name'].' from the database<br />';
            echo 
'<img '.$row['Image_Size'].' src="http://forums.x10hosting.com/tutorials/view_image.php?Image_ID='.$_GET['Image_ID'].'">';
        }
    }
    else {
        echo 
'File not selected';
    }
?>
put this in a file named view_image.php

there you have it, that's how you store and display images in a MySQL database, suggestions/comments appreciated

if you like this tutorial, please rep me for it

Last edited by tstivers; 07-17-2008 at 06:37 AM.
Reply With Quote
tstivers is offlineReport Post
x10 Sophmore

Tariqul Islam's Avatar

Join Date: Oct 2007
Posts: 130
Credits: 1,422
Tariqul Islam has much to be proud of
Location: Bangladesh

Quote  
07-18-2008, 01:40 PM
Re: How to store images in a MySQL database

WOW

That's a nice tot. Thanks for that
__________________
Reply With Quote
Tariqul Islam is offlineReport Post
x10Hosting Member

Dra_chan's Avatar

Join Date: Jan 2008
Posts: 27
Credits: 508
Dra_chan is on a distinguished road
Location: El Salvador

Send a message via MSN to Dra_chan
Quote  
07-19-2008, 01:30 AM
Re: How to store images in a MySQL database

That's pretty useful. I hope you get bored more often!
Reply With Quote
Dra_chan is offlineReport Post
x10Hosting Member

Join Date: Mar 2008
Posts: 44
Credits: 681
stalkio is on a distinguished road
Quote  
07-26-2008, 08:10 PM
Re: How to store images in a MySQL database

This is all created using PHPMyAdmin right? Where do you upload it to? - I have no idea where to implement it..but it sure sounds useful..
Reply With Quote
stalkio is offlineReport Post
x10Hosting Member

jspcodes's Avatar

Join Date: May 2008
Posts: 52
Credits: 564
jspcodes is on a distinguished road
Quote  
07-26-2008, 11:47 PM
Re: How to store images in a MySQL database

Every thing is fine.
But instead of using BLOB, one could store the image in the folder in the server and move the relative link to database table. IBM appreciated me for doing this in my project. They told me it has several advantages, like it avoids the database getting bigger & bigger.
__________________
www.tgmc.info
Reply With Quote
jspcodes is offlineReport Post
x10Hosting Member

brettzuya's Avatar

Join Date: Jun 2008
Posts: 30
Credits: 1,235
brettzuya is on a distinguished road
Quote  
07-27-2008, 02:09 AM
Thumbs up Re: How to store images in a MySQL database

Quote:
Originally Posted by tstivers View Post
i'm bored, and this seems like some nice information, so i'm going to write a tutorial for it... i learned how to do this from phpriot.com, but the tutorial is in my own words, not copied/pasted from their site

How to store/retrieve images in a MySQL database:

First off, the images are going to be stored in what is called a BLOB column

Q: What is a BLOB column?
A: A Binary Large Object, basically, it's used to store binary data in a MySQL database

Creating the image table:

You must create a table to store the images in.
Create a table named Images (or whatever you like) with 6 columns

Name the first column Image_ID with type tinyint and a length of 3, this should be an auto-incremented column

Name the second column Image_Type with type varchar and length of 25, we'll use this to store the mime type

Name the third column Image with type blob, this is where we will store the actual image

Name the fourth column Image_Size with type varchar and length of 25, this will tell us the size of the image

Name the fifth column Image_Category with type varchar and length of 25, this will be used to categorize the images

Name the sixth column Image_Name with type varchar and length of 50, if you havn't guessed, this will be the name of our image

the following code *should* create the table for you, although i havn't tested it
PHP Code:
create table Images (
    
Image_ID        tinyint(3)  not null default '0',
    
Image_Type      varchar(25not null default '',
    
Image           blob        not null,
    
Image_Size      varchar(25not null default '',
    
Image_Category  varchar(25not null default '',
    
Image_Name      varchar(50not null default ''
); 
Next we need the upload form

ok, i lied, the following is a direct copy/paste from phpriot

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html>
    <head><title>File Upload To Database</title></head>
    <body>
        <h3>Please Choose a File and click Submit</h3>
 
        <form enctype="multipart/form-data" action="upload_image2.php" method="post">
            <input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
            <input name="userfile[]" type="file" />
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>
this is just a basic form, put it in a .php file (we'll name it upload_image.php for this tutorial)

Create the uploader

Now we have to create the php script that does the actual uploading, this is another direct copy/paste from phpriot

PHP Code:
<?php
    
// check if a file was submitted
    
if(!isset($_FILES['userfile'])) {
        echo 
'<p>Please select a file</p>';
    }
    else
        {
        try {
            
upload();
            
// give praise and thanks to the php gods
            
echo '<p>Thank you for submitting</p>';
        }
        catch(
Exception $e) {
            echo 
$e->getMessage();
            echo 
'Sorry, could not upload file';
        }
    }
?>
don't run this script yet as there isn't an upload function created
as of yet, for now, just put it in a file (we'll name the file upload_image2.php for this tutorial)

basically, what this does, is check that the user actually entered a file, if so, it attempts to upload the image
if there is an error, it will return the error and abort

next we need to create the upload function

following is another copy/paste from phpriot

PHP Code:
<?php
    
// the upload function
    
function upload(){
 
    if(
is_uploaded_file($_FILES['userfile']['tmp_name'])) {
 
        
// check the file is less than the maximum file size
        
if($_FILES['userfile']['size'] < $maxsize)
            {
        
// prepare the image for insertion
        
$imgData =addslashes (file_get_contents($_FILES['userfile']['tmp_name']));
        
// $imgData = addslashes($_FILES['userfile']);
 
        // get the image info..
          
$size getimagesize($_FILES['userfile']['tmp_name']);
 
        
// put the image in the db...
          // database connection
          
mysql_connect("localhost""$username""$password") OR DIE (mysql_error());
 
          
// select the db
          
mysql_select_db ("$dbname") OR DIE ("Unable to select db".mysql_error());
 
        
// our sql query
        
$sql "INSERT INTO Images
                ( Image_ID , Image_Type ,Image, Image_Size, Image_Name)
                VALUES
                ('', '{$size['mime']}', '{$imgData}', '{$size[3]}', '{$_FILES['userfile']['name']}')"
;
 
        
// insert the image
        
if(!mysql_query($sql)) {
            echo 
'Unable to upload file';
            }
        }
    }
    else {
         
// if the file is not less than the maximum allowed, print an error
         
echo
          
'<div>File exceeds the Maximum File limit</div>
          <div>Maximum File limit is '
.$maxsize.'</div>
          <div>File '
.$_FILES['userfile']['name'].' is '.$_FILES['userfile']['size'].' bytes</div>
          <hr />'
;
         }
    }
?>
put this at the top of the upload_image2.php file

what this does:

1. check if the file is an allowed type
2. make sure the uploaded file isn't bigger than the max file size
3. format the binary data for insertion into the database
4. connect to the database
5. insert the data

now we must display the image

another copy/paste from phpriot

PHP Code:
<?php
    
// just so we know it is broken
    
error_reporting(E_ALL);
    
// some basic sanity checks
    
if(isset($_GET['Image_ID']) && is_numeric($_GET['Image_ID'])) {
        
//connect to the db
        
$link mysql_connect("localhost""username""password") or die("Could not connect: " mysql_error());
 
        
// select our database
        
mysql_select_db("Images") or die(mysql_error());
 
        
// get the image from the db
        
$sql "SELECT Image FROM Images WHERE Image_ID=0";
 
        
// the result of the query
        
$result mysql_query("$sql") or die("Invalid query: " mysql_error());
 
        
// set the header for the image
        
header("Content-type: image/jpeg");
        echo 
mysql_result($result0);
 
        
// close the db link
        
mysql_close($link);
    }
    else {
        echo 
'Please use a real id number';
    }
?>
put this in a file named get_image.php

Displaying the image and related information

another copy/paste

PHP Code:
<?php
    
// again we check the $_GET variable
    
if(isset($_GET['Image_ID']) && is_numeric($_GET['Image_ID'])) {
        
$sql "SELECT Image_Type, Image_Size, Image_Name FROM Images WHERE Image_ID=".$_GET['Image_ID'];
 
        
$link mysql_connect("localhost""username""password") or die("Could not connect: " mysql_error());
 
        
// select our database
        
mysql_select_db("Images") or die(mysql_error());
 
        
$result mysql_query($sql)  or die("Invalid query: " mysql_error());
 
        while(
$row=mysql_fetch_array($result)) {
            echo 
'This is '.$row['Image_Name'].' from the database<br />';
            echo 
'<img '.$row['Image_Size'].' src="http://forums.x10hosting.com/tutorials/view_image.php?Image_ID='.$_GET['Image_ID'].'">';
        }
    }
    else {
        echo 
'File not selected';
    }
?>
put this in a file named view_image.php

there you have it, that's how you store and display images in a MySQL database, suggestions/comments appreciated

if you like this tutorial, please rep me for it
i really appreciate of what you have done here,thats helpful info men!!your not only helping us all but you really did a good idea,thanks for the clues thats very useful
Reply With Quote
brettzuya is offlineReport Post
x10Hosting Member

Join Date: Mar 2008
Posts: 44
Credits: 681
stalkio is on a distinguished road
Quote  
08-05-2008, 07:18 AM
Re: How to store images in a MySQL database

I can't get this to work properly with the following message:

Quote:
File exceeds the Maximum File limit
Maximum File limit is
File Array is Array bytes
Thank you for submitting
Anyone getting this problem?
Reply With Quote
stalkio is offlineReport Post
x10Hosting Member

Join Date: Sep 2008
Posts: 3
Credits: 231
admbart is on a distinguished road
Quote  
10-03-2008, 06:22 PM
Re: How to store images in a MySQL database

This is a really helpful stuff, thanks guys. Sadly, doesn't seem to work on this site which stops binary file uploads.
Really want to add a facility where users can upload pictures which this site will then show.
Googled transloading, loading user images to a separate free image host, but not quite sure how to get it working from this site.
Need to be able to specify name and location of file in transload so that the right image can be shown.
Anyone done anything similar or found a way of allowing users to upload images here?
Edit:
Quote:
Originally Posted by stalkio View Post
I can't get this to work properly with the following message:



Anyone getting this problem?
Same here - this site won't let image uploads. Checked error log:
ALERT - uploaded file contains binary data - file dropped
V. frustrating

Last edited by admbart; 10-03-2008 at 06:22 PM. Reason: Automerged Doublepost
Reply With Quote
admbart is offlineReport Post
x10 Lieutenant

balaji2u's Avatar

Join Date: Sep 2008
Posts: 273
Credits: 2,222
balaji2u is on a distinguished road
Quote  
10-15-2008, 08:47 AM
Re: How to store images in a MySQL database

im just wondering where did u get the tut.. coz as far as i searched for exactly the same topic i failed ...
Great and good work ..
__________________
Want to Get A Free Domain No Scam,With in a Day or Minute.
Use the blow link.
Reply With Quote
balaji2u is offlineReport Post
x10Hosting Member

jspcodes's Avatar

Join Date: May 2008
Posts: 52
Credits: 564
jspcodes is on a distinguished road
Quote  
10-15-2008, 11:45 AM
Re: How to store images in a MySQL database

Thanks man. There is another way of uploading images instead of using BLOB or CLOB we can upload the picture to a folder in server and we can move the link to database.So if we need that file to be accessed we can use that link.
Because industry people preferred that method over this.

Kudos for your great effort in writing this tutorial
__________________
www.tgmc.info
Reply With Quote
jspcodes is offlineReport Post
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Similar Threads
Thread Thread Starter Forum Replies Last Post
New Site-Suggestions? mnoutside Review My Site 9 08-27-2008 08:01 AM
[PHP] MySQL and PHP Bryon Tutorials 23 08-17-2008 03:15 AM
How to create MySQL database and user Jesse Tutorials 11 06-04-2008 01:25 PM
FAQ Contest Corey Old Contests 41 10-16-2007 07:14 AM
PHP BB 2.0.16 Manual instalation GFIV Free Hosting 8 09-14-2005 01:40 PM


All times are GMT -5. The time now is 05:28 PM. Powered by vBulletin® Version 3.7.3
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO 3.2.0 RC7
vBCredits v1.4 Copyright ©2007 - 2008, PixelFX Studios

GBA Roms | Gas Suppliers | Loans | Loans | Loans