Jump to content

Display Image from DB?


barkster

Recommended Posts

I'm trying to display images from a database on my page but I can't figure out how.  Here is how I insert into the db

[code]
if ($handle = opendir('magik/')) {
echo "Running<br>";
  /* This is the correct way to loop over the directory. */
  while (false !== ($file = readdir($handle))) {
  $readfile = fopen('magik/'.$file, "r");
$data = addslashes(fread($readfile, filesize('magik/'.$file)));
mysql_query("INSERT INTO binary_data (bin_data,filename) VALUES ('$data','$file')", $conn) or die(mysql_error());
  }
  closedir($handle);
}
[/code]

Here is how I was tring to retrieve but I know isn't right.

[code]
<?php
$i=1;
echo("here");
do {
echo('<img src="'.$row_img['bin_data'].'" width="10" height="10"');
//echo "data".$row_img['bin_data'];
$i++;
if($i == 44) {
echo "<br>";
$i = 1;
}
}
while ($row_img = mysql_fetch_assoc($result));
?>
[/code]
Link to comment
https://forums.phpfreaks.com/topic/25628-display-image-from-db/
Share on other sites

It might be easier to store only the path to the file in the database, then store the images on your web server, then display them by retrieving filenames for your <img src>.

If you [b]really[/b] want to store the images in the database, I think you need a BLOB field.  Also, I expect you shouldn't use addslashes on a binary object like an image.

Then to retrieve the image you would write a script called something like getimage.php and have variables like 'name' (e.g. getimage.php?name=spaceship.jpg. You could then have something like <img src="getimage.php?name=spaceship.jpg">

In that script you'd do a "SELECT bin_data FROM binary_data WHERE filename='$name'" ($name being a validated $_GET['name']. Then depending on the image type (jpg, gif) you'd output the correct headers followed by the 'bin_data'. (e.g. header('Content-Type: image/jpeg') )

Sorry it's a bit of a pseduo-answer, but hope it helps!
Link to comment
https://forums.phpfreaks.com/topic/25628-display-image-from-db/#findComment-116974
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.