3

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.

2
  • You realize it's generally much better to store an image on disk and just store the URL to the image in a DB? Commented Aug 4, 2009 at 14:08
  • Can someone help by saying on how to get that "out" after storing it? Commented Aug 11, 2009 at 19:06

3 Answers 3

2

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(); 
Sign up to request clarification or add additional context in comments.

2 Comments

ooo am sorry, i am using Zend model class and $tablename = new Zend_model_Photo(); $tablename->save(); this way i am save the data... so i cant mention the "$sql = "INSERT INTO images (data) values(?)"; " over there....
You can grab the connection object from a Zend_Db_Table_Abstract derived class with $objectForZend_Db_Table->getAdapter()->getConnection()
1

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

Agreed, BLOB in DB will often be slow and contribute to DB bloat.
is there any additional function or method while insert a blob into db via Zend framework ? or simple Model class structure? i am unable to insert blob field, rest other fields are inserted but only problm is with the blog
0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.