Jump to content


Photo

Display Image from DB?


  • Please log in to reply
3 replies to this topic

#1 barkster

barkster
  • Members
  • PipPipPip
  • Advanced Member
  • 194 posts

Posted 30 October 2006 - 09:17 PM

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

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

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

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


#2 bqallover

bqallover
  • Members
  • PipPipPip
  • Advanced Member
  • 111 posts
  • LocationLeeds, UK

Posted 30 October 2006 - 09:43 PM

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 really 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!

#3 barkster

barkster
  • Members
  • PipPipPip
  • Advanced Member
  • 194 posts

Posted 30 October 2006 - 09:57 PM

Thanks, they have to be in the db for this project.  That is how I got it to work using a seperate page but I was hoping to just loop straight through them.  Thanks for the help

#4 barkster

barkster
  • Members
  • PipPipPip
  • Advanced Member
  • 194 posts

Posted 30 October 2006 - 09:58 PM

Forgot, I had to add addslashes cause when I did the insert query it was stoping when the data had a " ' " in it.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users