Otachan Otachan - 8 months ago 28
SQL Question

how to display an image from the database without using a directory

I looked up some tutorials from youtube, like 5 of them but they're all not working for me for some reason, I'm only getting broken image icon.

I've tried using a folder to get the images like

img src="images/$row['picture'];

But what I want is to display it straight from the database.

If possible please send me a code for it, so I will know if it's my browser or my coding.

I copied these codes but it's not even working


It doesn't show the image:


It is generally discouraged to approach it that way. <-(Good to know)

...it can still be done though and your use case may call for it...

With full credit to @Andomar:

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);