Yii 1.1: custom sql query results to CDetailView


This is a bried guide about displaying of custom sql query results.

The result of the query will display on CDetailView widget

Remember that the query have to returns only one row. In any case the code takes into only the first row-result

  • Prepare and execute the sql query
$connection = Yii::app()->db;
$command = $connection->createCommand('select * from your_table');
$row = $command->queryRow(); //executes the SQL statement and returns the first row of the result.
  • Convert the results to the appropriate for CDetailView format
$res = array();
    foreach ($row as $key=>$val) {
        $res[] = array('label'=>$key,'value'=>$val);
  • Display the data
$this->widget('zii.widgets.CDetailView', array(
'data' => array(), //to avoid error
'attributes' => $res,


  • If you want to change the name of the displayed columns you could either set alias on sql query
$command = $connection->createCommand('select col_1 as 'my name column',col_2 as 'my name column2' ... from your_table');

or make a match (with mapping array) in foreach loop.

  • If you not sure about the purity of the data you have to use
$res[] = array('label'=>$key,'value'=>CHtml::encode($val));

I show you now how to make the similar task using other Providers

With CSqlDataProvider

$sqlProvider = new CSqlDataProvider('select * from your_table');
$sqlProvider = $sqlProvider->getData();
$sqlData = $sqlProvider[0];
$this->widget('zii.widgets.CDetailView', array(
    'data' => $sqlData,

With CArrayDataProvider

$connection = Yii::app()->db;
$command = $connection->createCommand('select * from your_table');
$row = $command->queryRow();
$sqlData = new CArrayDataProvider(array($row));
$sqlData = $sqlData->getData();
$sqlData = $sqlData[0];
$this->widget('zii.widgets.CDetailView', array(
    'data' => $sqlData,

Total 2 comments

#14939 report it
Kostas Apazidis (KonApaz) at 2013/09/23 10:11am
RE: Easier with CSqlDataProvider

Yes it could be bone with CSqlDataProvider or CArrayDataProvider!

I will extend this wiki both of two aproaches. Thanks for your comment robregonm :)

#14938 report it
robregonm at 2013/09/23 09:41am
Easier with CSqlDataProvider?

I think, that could be more easily implemented with CSqlDataProvider. Similar results, more flexibility, more compatibility.

Leave a comment

Please to leave your comment.

Write new article