Entry
How can I store images in a database?
Dec 14th, 2001 05:37
Waldo Monster, Nathan Wallace, Mike Gohlke, Rob Curts, Lez Lytollis
The following snippet assumes that magic quotes are OFF for mysql
queries. Consequently, you must manually addslashes before storing.
HOWEVER, you do NOT need to use stripslashes as the retrieval from mysql
will do it regardless of the magic quotes setting. It's a bit wordy
(codey?) for completeness sake.
Example Table fubar:
OID Bigint(20) NOT NULL AUTO_INCREMENT, PRIMARY KEY
GRFX Blob NULL
<?
// Insertion Snippet
$lnk = mysql_pconnect("localhost","userid","password");
mysql_select_db("baz");
$fp = fopen("buff.jpg","r");
$bvar = fread($fp,filesize("buff.jpg");
fclose($fp)
$bvar = addslashes($bvar);
mysql_query("insert into fubar (grfx) values ('$bvar')");
// Retrieval / Viewing Snippet
$qry = mysql_query("select grfx from fubar where oid = '1'");
$garray = mysql_fetch_row($qry);
$grfx = $garray[0];
Header("Content-type: image/jpeg");
print($grfx);
?>
Rather than store an actual IMAGE in the database (because that can
quickly get very large)... why don't you just store the URL to the
image. Perhaps have all your images in one directory, like /dynimg/,
and for every insert into the table, just pull that out.
It would be easy to load that value from the database and do:
print ("<img src="$imageloc">);
You may also like to read the following article:
http://www.webtechniques.com/features/1998/02/lerdorf/lerdorf.shtml
For Windows users change
$fp = fopen("buff.jpg","r"); to $fp = fopen("buff.jpg","rb");