Yii: Get Column names from dynamic query

963 Views Asked by At

Is it possible to execute a query and just get the column names of the returned result set. I need the column names since the query is dynamic and I don't know the names of the columns.

I will use these column names for sorting when executing the query again.

You could refer to my Previous question to get the idea why I need it.

Thanks.

1

There are 1 best solutions below

0
Mark Eirich On

Depending on which PDO driver is in use, you can get column names from PDOStatement::getColumnMeta, once the statement has been executed.

Here is one way it can be done in Yii 1.1:

$command = Yii::app()->{db}
  ->createCommand('SELECT "." `Stop!`, current_time `Hammer Time`');
$reader = $command->query();

$sth = $command->getPdoStatement();
for ($i = 0; $i < $sth->columnCount(); $i++) {
  $col = $sth->getColumnMeta($i);
  print $col['name'].' ';
}