# Create simple report with export CSV This is generic Yii code to generate a simple report from an SQL query. The query has no parameters. ### QueryController.php The last method/function needs to be changed. The method can also be copied as much as needed. Change the code that is labeled with < and > in the last function. Open the controller the usual way: query/<name of action> ```PHP [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['POST'], ], ], 'access' => [ 'class' => AccessControl::className(), 'rules' => [ // when logged in, any user [ 'actions' => [], 'allow' => true, 'roles' => ['@'], ], ], ], ]; } private function executeQuery($sql, $title="no title", $export=false) { $result = Yii::$app->db->createCommand($sql)->queryAll(); if ($result) { // column names are derived from query results $data['col']=array_keys($result[0]); } $data['row']=$result; if ($export) { $this->exportExcel($data); } else { $data['title']=$title; return $data; } } public function exportExcel($data) { header('Content-type: text/csv'); header('Content-Disposition: attachment; filename="canvas-export' . date('YmdHi') .'.csv"'); foreach ($data['col'] as $key => $value) { echo $value.", "; } echo "\n"; foreach ($data['row'] as $line) { foreach ( $line as $key => $value) { echo $value.", "; } echo "\n"; } } public function action($sort='desc', $export=false) { // sort parameter is optional, export parameter determines if export to CSV needs to be given // specify query $sql="select column1 Header1, column2 Header2,.... from .... order by 3 $sort"; // specify report title $data=$this->executeQuery($sql, , $export); // specify sub title (descr, can also be omitted). return $this->render('output', [ 'data' => $data, 'action' => Yii::$app->controller->action->id, 'descr' => , ]); } } ``` ### View The view does not need any adaptations. ```HTML

".$descr.""; } ?>
'btn btn-primary', 'title'=> 'Export to CSV',]) ?>

#"; if ( $data['row'] ) { for($i=0;$i".$data['col'][$i].""; } } else { echo ""; } ?> "; echo ""; } for($i=0;$i".$item[$data['col'][$i]].""; } echo ""; } } ?>
Empty result set
".$nr."
```