I want to insert a image in blob format to db. how to write a program in zend framework. a simple form just choose one image and insert into db.
-
You realize it's generally much better to store an image on disk and just store the URL to the image in a DB?JasonDavis– JasonDavis2009-08-04 14:08:21 +00:00Commented Aug 4, 2009 at 14:08
-
Can someone help by saying on how to get that "out" after storing it?Dimitrios Mistriotis– Dimitrios Mistriotis2009-08-11 19:06:42 +00:00Commented Aug 11, 2009 at 19:06
3 Answers
In your Zend form create a file element:
$element = new Zend_Form_Element_File('fileElement');
Then you can insert the uploaded image to your DB in BLOB format like this:
$conn = new PDO("mysql:host='host';dbname='database'", 'userName', 'password');
$imagePath = $zendForm->fileElement->getFileName();
$image = file_get_contents('$imagePath');
$sql = "INSERT INTO images (data) values(?)";
$q = $conn->prepare($sql);
$q->bindParam(1, $image, PDO::PARAM_LOB);
$q->execute();
2 Comments
Read it in as a string using file_get_contents and store that.
That said, it is seldom a good idea to store the actual image data in the database. It is better practice to generate a unique filename and store that in the DB instead.
2 Comments
Here is some code to save the file in zend:
// This is to save in saveAction()
$source = $this->view->form->upload->getFileName();
$fp = fopen($source,'r');
$content = fread($fp,filesize($source));
// I don't use addslashes, because i already have that in my mapper
fclose($fp);
$model->image = base64_encode($content);
// Save here
// This is to read in imagesAction()
$this->_helper->Layout()->disableLayout();
$this->_helper->ViewRenderer->setNeverRender();
header('Content-Type: image/gif');
echo base64_decode($image);
exit;
I had alot of problems with it, try to make your save work and don't insert it into the database directly to test the reading. This won't make it possible unless you know the correct db encoding (which i don't).