A piece of my mind

Retrieving Image File from MySQL using PHP

Many people ask me about this.

Database example:
database name = “test”
table name = “image”
table column 1 = id, data type = int, special attributes = auto_increment, primary key
table column 2 = image, data type = blob

this is the sql script:

use test;
create table image (id int(11) NOT NULL auto_increment, image blob, PRIMARY KEY(id));

this is the php script:

<?
header(“Content-type: image/jpeg”); // act as a jpeg file
mysql_connect(“your_host”,”your_db_username”,”your_db_password”);
mysql_select_db(“test”); // use the ‘test’ database

$query = “select image from image where id = $id”;
$result = mysql_db_query(“test”,$query);

$row = mysql_fetch_array($result);
$img = $row[‘image’];

echo (“$img”);
?>

There you go, you will see the image that you store in MySQL database using blob data type.
Enjoy! :D

20 Comments

  1. Tue, 17 Jul 2007    

    this query is not valid in my php mysql.image uploading process..this query i work in my prg..follwoing error occur ..

    Parse error: syntax error, unexpected ‘:’ in C:\xampp\htdocs\im1.php on line 2

    please help me…

  2. Wed, 18 Jul 2007    

    @ mahendran
    what is on line 2 in your im1.php ?

  3. Darini Darini
    Tue, 4 Dec 2007    

    Hi,
    Its working fine with image. Am trying to use the same for audio and video file. But its not working y?
    Can u send me the code for storing and retriving audio and video file from mysql database? please..

  4. rax rax
    Wed, 19 Dec 2007    

    This does not work for me
    I get the link to my site and that’s it

    http://localhost/pages/imageview.php

  5. gubbachchi gubbachchi
    Thu, 7 Feb 2008    

    Hi,
    You have given the code to retrieving image from mysql, can you please give me the code to store image in mysql.

    With regards,

  6. bhavin bhavin
    Mon, 3 Mar 2008    

    your code just hang out while displaying image

    it take lot of time or i should say it hang up while displaying page

  7. Fri, 7 Mar 2008    

    @bhavin
    I created that script a long time a go, still using php 4 and I forgot what version of MySQL that I use back then. Maybe you have to revise the script a little bit to make it work. Or maybe there are a better way to do that right now in the blogosphere

  8. Sun, 29 Jun 2008    

    This code is not working.Please send complete code to store and display.
    Thanks in advance
    This code showing like this

    Warning: Cannot modify header information – headers already sent by (output started at C:\wamp\www\image_galary\show.php:7) in C:\wamp\www\image_galary\show.php on line 8
    ÿØÿàJFIFddÿìDuckyw,.ÄÞä±&äë^ ¯1¬½úV1¢Av¨Ú?j\›þ†DÁ„ §’º_QV®äLe…¦sªÙÑŸ³ì¸›„AåÄÅeŸ!”R1³o5úøWEsZæuy“¹[Û Yæ¾ç^ÔÐō•4Â)Â¥ãÔà:@שխ-8·d¦/qwnÃ…í&Ly¸1(1þá$,x¢LGÍìm9W¡±ÌÜڍu‡-øû{#»vyí½Ï·œŒK¤ÑYrqÛæF<5槑¯{c‘‘˜y¼Ž=¶§°WCÅ“^€½h ôlh..GÝR@ä£ÄÐT½EíDÃœqt Tõ[ð¹·.M쨔úmÝ @س˜¬‰Õû6s¯—戟â¾”«“ßV_$vvDØ“aã­ejåÕKøʾ¹K*2’@,TóÒ±šá×MܶâijH#/`Ãœ#T¼âV2Þ𘜡[•ÒÜj‘l柚&«ð¶ŽTÄ/Ý·è,V“{Ël†â!‡È¿‰µëJìGu-Ê´ºÆѱ`m˜©‹…A* VÑÖ´ÏT¬}1‹j²’sƒ&S”t@Êx·ûS ¦B€°Y ŽÜrÁÿ~³úP7ˆÇÓjÐCîxÃ…$û€yò5¤Â){†M£-S,ÛçÐH51¿?úMSË ‰Zq²`ȉfÖHÅ“]]MÁx•›*F2Æ’£#¨*ÂÄ ?ê¡™“sÚœ®Zž¶Æo•Ç1u±÷s÷ð¨ÂrçXþŽïø¡&ÆÅûˆÝA]$T‘z´df*VEþ™#X»GÓ®öØ2$m·>=¿G\yãû3«^¾“ãÑÓza9u½¯lÞ„,3åÅȐXÃ…WAø«³ÛãSO—*öŸy°ÿSPe¹6¬–ùÝcÓæ?Â¥0dïlÆ„õXÉ’ó>¿¬‰; \›f‚¯»wjÉ•ÿÌÙÈŸ-®$Å“kC™¿2*“`ã„U¹b¬Ú’y“V!‰TƒÁu5″Bh0–4‘ 8¸I¼ –FÿÜýÑ1ƃÿ[üéÂ…þ·â}ÕLÌ‹NÅ°cmtF:Â¥meӖ’øV•Œ ˜â$…Q©« !%¹ó4(€ B 0¸4#¦ôÞqòä)Õ?¡5³zw”³GosTEiéÛ}y*=ÊOê*~0îOðÆ’,Ã’?±@_¸x½©³cê¸ÁØs{·ät©ñ-H ‘ôÀaW„·¦s° p˜Ñ¯Ô}´l( (ô­‰ @Z€µ@Z€¶” Ò§ N…ð a@¶ -@Z-@PÿÙ

    • Tani Tani
      Sat, 12 Jan 2013    

      i am having the same problem…. please need help

  9. Sun, 4 Jan 2009    

    this is the output i get when i run this script.
    please help with the right script to get the image in is original format… thanks

    �PNG  ��� IHDR�������������0 ���sBIT|d���� pHYs��t��tk$�����tEXtCreation Time�12/05/08|�����tEXtSoftware�Adobe FireworksO�N��’�prVWx�u{ip�vG~ZfF ���&n���W� �

    • Mon, 5 Jan 2009    

      @bernd
      that script was using older version of PHP and MySQL. I haven’t test it yet using the current version

  10. Sun, 10 May 2009    

    I would like to ask please, do not have examples of programs based on the histogram image retrieval using the PHP language, if I have sent to my email-wanto03@gmail.com. please help

  11. Fri, 31 Jul 2009    

    tolong kasih pencerahan….
    bagaimana caranya menyimpan nilai bin-bin histogram kedalam database menggunakan script php?dan bagaimana cara menampilkan dalam halaman browser. tolong dikirim kealamat E-mail saya ya!mohon konfirmasinya dan terima kasih

  12. kuban kuban
    Fri, 23 Oct 2009    

    thanx it’s great and works fine

  13. Mon, 5 Mar 2012    

    plz tl the correct code for retriving images from database using php

  14. Bongani Bongani
    Fri, 27 Jul 2012    

    Hello every one here are codes to help you save and retrieve image and audio from your database.

    If you don’t understand or you have a problem please send me your code bgn90@yahoo.com

    First we will store image to database.

    Create database and a table that you will store your files.
    —— creating table (create it using mysql commander), Let’s say we are using Database “Africa”…here’s a code that creates a table under database “Africa”.

    Create table files (id int auto_increment not null, primary key(id),name varchar(60)not null,type varchar(60)not null,size int(11)not null,content mediumBLOB not null);

    *note that MediumBLOB limits the file to 6MB in size.

    Then let’s create a file that will upload image and Audio. With this file you’ll be abwle to upload both images and audio files. We will then name our file upload.php

    Upload

    0){
    $fileName = $_FILES[‘userfile’][‘name’];
    $tmpName = $_FILES[‘userfile’][‘tmp_name’];
    $fileSize = $_FILES[‘userfile’][‘size’];
    $fileType = $_FILES[‘userfile’][‘type’];

    $fp = fopen(tmpName,’r’);
    $content = fread(fp,filesize($tmpName));
    $content = addslashes($content);
    fclose(fp);

    If (!get_magic_qoutes_gpc(){

    $fileName = addslashes(fileName);
    }

    $dbcon = mysql_connect(“localhost”,”username”,”password”);
    mysql_select_db(“Africa”,dbcon);
    $query = ‘INSERT INTO files (name,size,type,content)VALUES(“‘.$fileName.'”,”‘.$fileSize.'”,”‘.$fileType.'”,”‘.$content.'”)';

    mysql_query($query) or die (‘Error, Query failed’);
    mysql_close($dbcon);

    echo ” files “.$fieName.” Is added to Database Africa”;
    }
    ?>

    Copy and paste the above code and run it, do not go for the next code if this one is not running, email me your problem if you can not run the page bgn90@yahoo.com .

    I recommend that you upload at least 5 images to your database before moving to this step
    Let’s now retrieve what we have saved to our database.

    Create a php file to retrieve both images and audio. We will name the file engine.php

    After saving this file engine.php

    We will need a file that will link you to this engine.php file. Let’s quickly do that, we will need another php file to retrieve from this file.

    Let’s name this file link.php

    viewer

    <?php
    $dbcon = mysql_connect("localhost","username","password&quot;);
    Mysql_select_db('Africa',$dbcon);

    $query = "select I'd, name from files";
    $result = mysql_query($query) or die ("error, query failed&quot;);

    If(mysql_num_rows($result)==0)
    {
    Echo "database Africa is Empty “;
    }

    Elese

    {
    While (list($id,$name) = mysql_fetch_arra($result))
    {
    ?>
    <a href='engine.php?id=’ Id=” >

    We are now done, copy all the files name the accordingly, and see how you can view you data from the database this is how we view images and audio from the database. Not that the link.php file will show the data in your database in a form of anchors/link, when you click them it they will link you to the engine.php file. Same as when you want to ad an image to your php file, use e.g <?php echo "This is my image “; ?>

    Copy that e.g code and paste it and save it as php file, and see what I mean.

  15. khaja moinuddin khaja moinuddin
    Tue, 19 Mar 2013    

    i want to image retrieve program and image gallery program
    plz help me

  16. khaja moinuddin khaja moinuddin
    Tue, 19 Mar 2013    

    plz i want to image album program

  17. Mon, 11 Nov 2013    

    kpq gak kelihatan ya bro imagenya ? padahal udah bener nulis scriptnya x_X

  18. Sat, 12 Jul 2014    

    Thakyou very much for share. now I know and that usefull for me . :)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Friends

Already a member?
Login
Login using Facebook:
Last visitors

Categories

Ubuntu Linux