1

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.

Community
  • 1
  • 1
neophyte
  • 1,726
  • 3
  • 15
  • 21
  • Tell us, why dont you use GII Generated PHP-Models which will be Yii conform and very comfortable? In that way .. you know any columns before executing any query. – lin Aug 08 '14 at 10:08
  • the query returns column names using SQL Pivot function.. I dont know how do I work using models with that.. – neophyte Aug 08 '14 at 10:09
  • GII is a main feature of Yii. MVC Pattern, thats why you should use frameworks like Yii. Checkout this: http://www.yiiframework.com/doc/guide/1.1/en/topics.gii#using-gii and try generate your models by a given Database schema. 1) Create your DB, 2) start/configure GII 3) generate your PHP-Models by using your DB-Schema and GII. Than you can access your attributes (which will be same as your DB-Columns) like `$model->attributes` – lin Aug 08 '14 at 10:11

1 Answers1

1

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'].' ';
}
Mark Eirich
  • 10,016
  • 2
  • 25
  • 27