how to display image stored in database

hi all i am trying to store the image path in database and try to show the image on screen

the code if used in controller




public function actionShowimage() {

        $data = Pic::model()->findByPk($_GET['id']);

        echo '<img src="D:\Dev\Apache\htdocs\apartmentf\images\dadmom1.png;base64,' . chunk_split(base64_encode($data->img)) . '" />';

        exit();

        }




in view




public function actionShowimage() {

        $data = Pic::model()->findByPk($_GET['id']);

        echo '<img src="D:\Dev\Apache\htdocs\apartmentf\images\dadmom1.png;base64,' . chunk_split(base64_encode($data->img)) . '" />';

        exit();

        }



Or can i directly extract the path stored in database and give it in src of img tag?




<div class="content">

        <?php

        $source=array();

         $source= Yii::app()->db->createCommand()

			->select('file_name')

			->from('pic')

			->where('id=:id', array(':id'=>$model->id))

			->queryColumn();

           echo '<img src="'.$source.'"/>';


        ?>

 </div>



i have no idea what is correct procedure to do. please help me

Note: You posted twice your controller code ;)

Of course you should use the file infos from the database cause your first solution with absolute paths D:\… will only work on your local dev machine but not on a hosting environment with a different OS and/or directory structure.

I prefer to save the path and the filename in seperate db fields. It’s then easier to display only the filename.

Furthermore, I would suggest you to use / instead of \ directory seperators.

See the following page with further informations about that.

[url=&quot;http://alanhogan.com/tips/php/directory-separator-not-necessary&quot;]

Portable PHP code: DIRECTORY_SEPERATOR is not necessary[/url]

Edit:

Sorry, wrote wrong answer to display image from filesystem but you need to display image from blob field in database.

See this wiki: Saving files to a blob field in the database

You need an action like actionDisplaySavedImage() to achieve your goal.

now i tried this code for displaying images form blob field in database

controller code:




  public function actionDisplaySavedImage()

{


    $model=$this->loadModel($_POST['Pic']['id']);





    header('Pragma: public');

    header('Expires: 0');

    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

    header('Content-Transfer-Encoding: binary');

    header('Content-length: '.$model->file_size);

    header('Content-Type: gif');

    header('Content-Disposition: attachment; filename='.$model->file_name);


        echo $model1->file_name;

}




in _form.php i have did this.




<?php echo CHtml::link('image',array('displaySavedImage','id'=>$model->primaryKey)); ?>




but when i run this it saya undefined index:id

please help me


 public function actionDisplaySavedImage()

{


    $model=$this->loadModel($_POST['Pic']['id']);





    header('Pragma: public');

    header('Expires: 0');

    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

    header('Content-Transfer-Encoding: binary');

    header('Content-length: '.$model->file_size);

    header('Content-Type: gif');

    header('Content-Disposition: attachment; filename='.$model->file_name);


        echo $model1->file_name;

}



Error is in the code




    $model=$this->loadModel($_POST['Pic']['id']);



As we have set the ID in the link section, so, you should do it as




    $model=$this->loadModel($_GET['id']);



I tried even with that but i didnt get it.i got the same error.Do i have to mention any source attribute for it.

please help me.I think there is some problem with controller code.




<?php echo CHtml::link('image',array('NameofControlloer/displaySavedImage','id'=>$model->primaryKey)); ?>



Replace

NameofControlloer with your controller

I am able to call function in the controller but it tells

undefined index:id

is it not getting posted.please guide me through that code:

Do a




print_r($_GET);



in the controller to see what values are set.

am i in the right path of displaying the image from database into view?

You should post your code over here

Model, Controller & View where you want to display the image

@Nalajala:

It’s really annoying that you don’t post any code!! >:(

How are we supposed to help you out when we have nothing to go on?

Could you please post the code for the action you have problems with?

And maybe the view too?

Thanks. ;)

hi jacmoe

i have been trying to display the image in view from my mysql database.fields i have in my database are

id(primary key)

image

file_name

file_type

file_size

file_content

i am able to upload my image to database but i am not able to display it in my view.I wrote the following action in my controller




  public function actionDisplaySavedImage()

{

              


			$model=$this->loadmodel($_GET['id']);




    header('Pragma: public');

    header('Expires: 0');

    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

    header('Content-Transfer-Encoding: binary');

    header('Content-length: '.$model->file_size);

    header('Content-Type: png');

    header('Content-Disposition: attachment; filename='.$model->file_name);


        echo $model->file_name;

}




in my _form.php

i created a link




<?php echo CHtml::link('my_link_name',array('displaySavedImage','id'=>$model->primaryKey)); ?>



when i click the link in browser it prompts an error

undefined index:id

please help me

thanks

when i do print_r($_GET) i seen an empty array

do i have to modify any code in _form.php for my link now.

<?php echo CHtml::link(‘my_link_name’,array(‘displaySavedImage’,‘id’=>$model->primaryKey)); ?>

should i replace this code and is my controller code in the right way,because when i do a print_r($_GET) i see an empty array

please help me

To be sure the image display logic work replace the $_GET[‘id’] with a hardcoded primary key which is available in your database.




  $model=$this->loadmodel(1); // replace 1 with an existing row in your db



Then try if you see the image.

So, the error says undefined index:id which for me is a indication for that you don’t pass correctly the $model to the view (e.g _form.php).

The fact that the $_GET output is empty fortified my suspicion.

Please post the complete action’s that are displaying the views which are not working. Also post the renderPartial part of the view which is loading the _form.php. Maybe you pass the $model to the view which call renderPartial(’_form’) but don’t pass the $model also to the _form.php view so there it is not available which would explain the error message.

And please use code tags ([code ] [ /code] without spaces) to post code cause it is much more readable, thanks.

Also try to learn to debug errors better by yourself (do print_r’s for different var’s and look at the values; replace variables with hardcoded values to see if it works in principle; try to debug the code using breakpoints with your IDE e.g netbeans,…). I bet it is a really simple bug in your code which you normally should find by yourself at the latest after our hints here in the forum.

when i tried with the


$model=$this->loadmodel(1);

it says webpage not found

No webpage was found for the web address: http://localhost/apart122/index.php/pic/displaySavedImage/

Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be found.

my controller code:


<?php


class PicController extends Controller

{

	/**

	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning

	 * using two-column layout. See 'protected/views/layouts/column2.php'.

	 */

	public $layout='//layouts/column2';


	/**

	 * @return array action filters

	 */

	public function filters()

	{

		return array(

			'accessControl', // perform access control for CRUD operations

		);

	}


	/**

	 * Specifies the access control rules.

	 * This method is used by the 'accessControl' filter.

	 * @return array access control rules

	 */

	public function accessRules()

	{

		return array(

			array('allow',  // allow all users to perform 'index' and 'view' actions

				'actions'=>array('index','view','displaySavedImage'),

				'users'=>array('*'),

			),

			array('allow', // allow authenticated user to perform 'create' and 'update' actions

				'actions'=>array('create','update'),

				'users'=>array('@'),

			),

			array('allow', // allow admin user to perform 'admin' and 'delete' actions

				'actions'=>array('admin','delete'),

				'users'=>array('admin'),

			),

			array('deny',  // deny all users

				'users'=>array('*'),

			),

		);

	}


	/**

	 * Displays a particular model.

	 * @param integer $id the ID of the model to be displayed

	 */

	public function actionView($id)

	{

		$this->render('view',array(

			'model'=>$this->loadModel($id),

		));

	}


	/**

	 * Creates a new model.

	 * If creation is successful, the browser will be redirected to the 'view' page.

	 */

	public function actionCreate()

	{

		$model=new Pic;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['Pic']))

		{


			$model->attributes=$_POST['Pic'];

            $model->image=CUploadedFile::getInstance($model,'image');

			if($model->save())

				$this->redirect(array('view','id'=>$model->id)

                                				);




		}


		$this->render('create',array(

			'model'=>$model,

		));

	}


      	/**

	 * Updates a particular model.

	 * If update is successful, the browser will be redirected to the 'view' page.

	 * @param integer $id the ID of the model to be updated

	 */

	public function actionUpdate($id)

	{

		$model=$this->loadModel($id);


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['Pic']))

		{

			$model->attributes=$_POST['Pic'];

			if($model->save())

				$this->redirect(array('view','id'=>$model->id));

		}


		$this->render('update',array(

			'model'=>$model,

		));

	}


	/**

	 * Deletes a particular model.

	 * If deletion is successful, the browser will be redirected to the 'index' page.

	 * @param integer $id the ID of the model to be deleted

	 */

	public function actionDelete($id)

	{

		if(Yii::app()->request->isPostRequest)

		{

			// we only allow deletion via POST request

			$this->loadModel($id)->delete();


			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser

			if(!isset($_GET['ajax']))

				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));

		}

		else

			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

	}


        public function beforeSave()

    {

        if($file=CUploadedFile::getInstance($this,'image'))

        {

            $this->file_name=$file->name;

            $this->file_type=$file->type;

            $this->file_size=$file->size;

            $this->file_content=file_get_contents($file->tempName);

        }


    return parent::beforeSave();

    }

	/**

	 * Lists all models.

	 */

	public function actionIndex()

	{

		$dataProvider=new CActiveDataProvider('Pic');

		$this->render('index',array(

			'dataProvider'=>$dataProvider,

		));

	}


	/**

	 * Manages all models.

	 */

	public function actionAdmin()

	{

		$model=new Pic('search');

		$model->unsetAttributes();  // clear any default values

		if(isset($_GET['Pic']))

			$model->attributes=$_GET['Pic'];


		$this->render('admin',array(

			'model'=>$model,

		));

	}




	/**

	 * Returns the data model based on the primary key given in the GET variable.

	 * If the data model is not found, an HTTP exception will be raised.

	 * @param integer the ID of the model to be loaded

	 */

	public function loadModel($id)

	{

		$model=Pic::model()->findByPk((int)$id);

		if($model===null)

			throw new CHttpException(404,'The requested page does not exist.');

		return $model;

	}

    public function actionDisplaySavedImage()

{

    $model=$this->loadModel(1);


    header('Pragma: public');

    header('Expires: 0');

    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

    header('Content-Transfer-Encoding: binary');

    header('Content-length: '.$model->file_size);

    header('Content-Type: '.$model->file_type);

    header('Content-Disposition: attachment; filename='.$model->file_name);


        echo $model->file_content;

}


	/**

	 * Performs the AJAX validation.

	 * @param CModel the model to be validated

	 */

	protected function performAjaxValidation($model)

	{

		if(isset($_POST['ajax']) && $_POST['ajax']==='pic-form')

		{

			echo CActiveForm::validate($model);

			Yii::app()->end();

		}

	}

}



_form.php


<div class="form">


<?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'pic-form',

	'enableAjaxValidation'=>true,

	'htmlOptions'=>array('enctype'=>'multipart/form-data'),

)); ?>


	<p class="note">Fields with <span class="required">*</span> are required.</p>


	<?php echo $form->errorSummary($model); ?>


	<div class="row">

		<?php echo $form->labelEx($model,'image'); ?>

        <?php echo CHtml::activeFileField($model, 'image'); ?>

		<?php echo $form->error($model,'image'); ?>

	</div>

      <?php echo CHtml::link('my_link_name',array('displaySavedImage','id'=>$model->primaryKey)); ?>


<div class="row buttons">

		<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

	</div>


<?php $this->endWidget(); ?>


</div><!-- form -->

ok instead id if i give 1 there a file is getting downloaded of the given content type and when i say

echo $model->image

society.gif(text format) is being displayed.this society.gif is in my database

where am i going wrong

help me