Page 1 of 1

Inserting image into database problem ??

Posted: Tue Apr 03, 2007 3:27 am
by PHPycho
Hello forums !!
I used the following code to upload the image in the DB

Code: Select all

$tmp_name 	= $_FILES['file']['tmp_name'];
		$filesize 	= filesize($tmp_name);
		$filename 	= $_FILES['file']['name'];
		$file_type 	= $_FILES['file']['type'];
		$contents 	= fread(fopen($tmp_name,'rb'),$filesize);
		//fclose($tmp_name);
		//echo $contents;
		//$contents = base64_encode($contents);	
		$addFile = "INSERT INTO mantis_bug_file_table
				   (bug_id,filename,filesize,file_type,date_added,content)
				   VALUES
				   ('$idbug','$filename','$filesize','$file_type',NOW(),'$contents')";
		//echo $add5;
		$resultFile = mysql_query($addFile) or die(mysql_error());
when i run this code , apache got down and nothing worked.
when i removed the $contents from the query or encoded the $contents with base64_encode() then it went right.
What's the problem with reading the upload image and inserting it in the database or this is not the way of inserting image into database ?
Any Idea ? Please Help
Thanks in advance to all of you !

Posted: Tue Apr 03, 2007 3:38 am
by Luke
why don't you just store the location of the image in your database? Why recreate a filesystem within a database, when one is readily available? I'd do something more along the lines of:

Code: Select all

bug_id		location			filesize		filetype		date_added
1		/images/test.png		    300			image/png		2007-04-23
2		/images/some_image.jpg	  220			image/jpg		2007-04-02
3		/images/test.gif		    43			 image/gif		2007-02-22

Posted: Tue Apr 03, 2007 4:23 am
by PHPycho
Anyway i got the solution
what i did ?
i just placed the addslashes() in the $contents and inserted.and it worked...
Now One more Question ?
How to retrive the image from database ?
Thanks in advance to all of you !

Posted: Tue Apr 03, 2007 6:54 am
by mikeq
No offence PHPycho but did you even try googling for the answer

http://www.google.co.uk/search?hl=en&q= ... Bphp&meta=

Posted: Tue Apr 03, 2007 9:51 am
by pickle
Ya, this has been discussed before - likely even here on the forums.

The technique essentially boils down to you writing a PHP file that you reference like an image file. In the <img> tag, call your image file & pass along an image id in the URL. The PHP file will then read the appropriate image data out as binary data, fire off the appropriate header, then output the binary data from the db.