Json respond all datra from database

Hi sorry i’m totaly new in programming

Below is the code i edit from my company existing project and edit it in one of the controller.

public function actionIndex()

	{


        $Criteria = new CDbCriteria();


        $model = FeatureImage::model()->find($Criteria);


        


        if (empty($model)) $this->__fail('Not found');





        $response = array(


            'id' => $model->id,


            'image' => $model->image_name,


            'SortOrder' => $model->sortOrder,


            'Destktop Path' => $model->image_1,


        );





        echo json_encode($response);


        exit();


}

It is work with output

{"id":"xx","image":"Image xx","SortOrder":"xx","Destktop Path":"xxx.jpg"}

Just can anyone help me how to list all data in database ? Becuz it just echo first data from the database… i wan it echo all data. Please help thanks.

Hi,

find() method returns one DB record, what U need here is findAll (returns array of all records matching given criteria)


$models = FeatureImage::model()->findAll($Criteria);

after that I suppose U will need to go trough foreach and populate $result array:




$response = [];

foreach ($models as $model) {

    $response[] = array(

      'id' => $model->id,

      'image' => $model->image_name,

      'SortOrder' => $model->sortOrder,

     'Destktop Path' => $model->image_1,

    );

}



1 Like

THX!!! It is work!!

1 Like

However found out another problem which is

let said in mysql the correct path will be "/images/feature/562d9ff8173a88.26956287.jpg"

but json respond as below

"\/images\/feature\/562d9ff8173a88.26956287.jpg"

any idea on it?

Hello jongyanlaw,

If you are using ajax you can lack option: dataType: ‘json’

ok thank you.