store images in a mysql database

Started on the old forum in January 2011 · view the original in the archive · old links redirect here

No replies · 625 views · started 15 years ago · 2 min read

Anshul Senior · 296 posts #1

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.
$handle = fopen("testpic.jpg", "rb");
$img = fread($handle, filesize('testpic.jpg'));
fclose($handle);
//die($img);
$img = base64_encode($img);
$sql = "insert into pictures values(null,'$img','$extension')";

get images out of mysql database

$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

<img src="test02.php"/>

mysql image tble type

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.

Write your reply now; next you create a free account (or sign in) and it is posted right away. Sign in to reply.

Similar topics

Keyboard shortcuts

g f
Go to forums
g h
Go to your feed
g m
Go to messages
r
Reply (in a topic)
/
Search
j
Next post
k
Previous post
?
This list
Ctrl/⌘ + Enter
Send what you are writing
Ctrl/⌘ + B / I
Bold / italic while writing
Esc
Close