How To Get Field Name From Dynamic Table

can any one :rolleyes: plz help me to get the field name from dynamic table

The schema property of CDbConnection returns a CDbSchema object, which has a getTable() method returning a CDbTableSchema object.

You’ll need to iterate through the CDbColumnSchema objects returned by the columns property to get the column details. If you just need column names, use the columnNames property.




foreach (Yii::app()->db->schema->getTable('blah')->getColumnNames() as $columnName)

{

    // Do things

}



thank you for replying me. :D

but my problem is :-[ you mention ->getTable(‘blah’)

it was an a table name but in my application i h’v find the the table name from user entered queries for example “select * from school” here the table name is school.then how to find the table name from executing queries… :-X

Thanks in advance

That sounds exceptionally risky. What sort of application are you developing?

i’m developing an sql query window .which ex ecutes sql queries :(

Well, assuming that you have complete trust in your users, you can just do the following:




$command = Yii::app()->db->createCommand($sql);

try

{

    $result = $command->queryAll();

}

catch (Exception $ex)

{

    // Handle exception

}



You don’t need to parse the query if you just want to run it against the database.

Docs here.

Thx again keith.

I actually got the output i mean i got the column values.But i require column name also .that was my problem :blink:

The column name is part of the result. Following on from my code above:




foreach ($result as $row)

{

    foreach ($row as $columnName => $columnValue)

    {

        // ...

    }

}



Of course, the column name will only be available if the query returned at least one row. If you’re trying to build a table, you’d do something like the following in the view:




<? if (!count($queryResult)): ?>


    No results were found.


<? else: ?>


    <table>


        <tr>

            <? foreach(array_keys($queryResults[0]) as $columnName): ?>

                <th><?= CHtml::encode($columnName); ?></th>

            <? endforeach; ?>

        </tr>


        <? // Now output data ?>


    </table>


<? endif; ?>



Thank You So Much Keith My problem Solved ;D