Monday 11 June 2012

Insert And Retrieve Images From Mysql Database in PHP

Insert and Retrieve Images From Mysql Database in PHP



First you create a MySQL table to store images, like for example:

create table testblob (
    image_id        tinyint(
3)  not null default '0',
    image_type      varchar(
25) not null default '',
    image           blob        
not null,
    image_size      varchar(
25) not null default '',
    image_ctgy      varchar(
25) not null default '',
    image_name      varchar(
50) not null default ''
);

Then you can write an image to the database like:
$imgData = file_get_contents($filename);
$size = getimagesize($filename);
mysql_connect(
"localhost", "$username", "$password");
mysql_select_db (
"$dbname");
$sql =
"INSERT INTO testblob
    ( image_id , image_type ,image, image_size, image_name)
    VALUES
    ('', '{$size['mime']}', '{$imgData}', '{$size[3]}',
     '{$_FILES['userfile']['name']}')"
;
mysql_query($sql);

You can display an image from the database in a web page with:
$link = mysql_connect("localhost", "username", "password");
mysql_select_db(
"testblob");
$sql =
"SELECT image FROM testblob WHERE image_id=0";
$result = mysql_query(
"$sql");
header(
"Content-type: image/jpeg");
echo mysql_result($result,
0);
mysql_close($link);

No comments:

Post a Comment