store images in a mysql database

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    store images in a mysql database

    Reasons to store your images (binary files) in a database:

    1. Storing in a database allows better security for your files and images.
    2. Eliminates messy directory and file structures (this is especially true when users are allow to contribute files).
    3. Files/Images can be stored directly linking to user or advertiser information.

    You may want to reconsider storing your binary files in the database. Here are some reason you may not want to:

    1. You can't directly access your files using standard applications such as FTP.
    2. If you database becomes corrupt, so do your files.
    3. Migrating to a new database is made more difficult
    4. Pulling images from a database and displaying them is slower than using file access.
    PHP Code:
    $handle fopen("testpic.jpg""rb");
    $img fread($handlefilesize('testpic.jpg'));
    fclose($handle);
    //die($img);
    $img base64_encode($img);
    $sql "insert into pictures values(null,'$img','$extension')"
    get images out of mysql database

    PHP Code:
    $sql "select pic, ext from pictures where id='1'";

    $result mysql_query($sql) or die('Bad query at 12!'.mysql_error());

    while(
    $row mysql_fetch_array($result,MYSQL_ASSOC)){

    $db_img $row['pic'];
    $type $row['ext'];


    }

    $db_img base64_decode($db_img); //print_r($db_img );

    $db_img imagecreatefromstring($db_img);
    if (
    $db_img !== false) {
    switch (
    $type) {
    case 
    "jpg":
    header("Content-Type: image/jpeg");
    imagejpeg($db_img);
    break;
    case 
    "gif":
    header("Content-Type: image/gif");
    imagegif($db_img);
    break;
    case 
    "png":
    header("Content-Type: image/png");
    imagepng($db_img);
    break;
    }


    }
    imagedestroy($db_img); 
    usage
    Code:
    <img src="test02.php"/>
    mysql image tble type

    Code:
    mysql> CREATE TABLE images (
         > id tinyint(3) unsigned NOT NULL auto_increment,
         > image blob NOT NULL,
         > PRIMARY KEY (id)
         > );
    Tip: To be able to insert images that are bigger than 1MB you have to increase the max_allowed_packed option in the server configuration file. You can change that in the Startup Variables section in the MySQL Administrator on the Networking page.


    Note: data is copied from various sources.
Working...
X