Mask Mask - 1 year ago 51
PHP Question

How can I store and retrieve images from a MySQL database using PHP?

How can I insert an image in MySQL and then retrieve it using PHP?

I have limited experience in either area, and I could use a little code to get me started in figuring this out.

Answer Source

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 = sprintf("INSERT INTO testblob
    (image_type, image, image_size, image_name)
    ('%s', '%s', '%d', '%s')",

You can display an image from the database in a web page with:

$link = mysql_connect("localhost", "username", "password");
$sql = "SELECT image FROM testblob WHERE image_id=0";
$result = mysql_query("$sql");
header("Content-type: image/jpeg");
echo mysql_result($result, 0);