How to get all table and column names from a database in Yii Framework

I am working on a module where I want to execute a dynamic dependent drop down table and column name.

Ex. Extract all the table names and display them in the drop-down fields, and after selecting a specific table, I want to display the entire column name in the drop-down list box again.

Problems:

1) How to get all table name from db?

2) and how to get all column name from table?

I tried several articles and forums such as http://www.yiiframework.com/forum/index.php/topic/5920-how-can-i-get-the-actual-full-table-name/ but it doesn’t work .

Any help would be appreciated.

thanks

+4
source share
3 answers

This is pretty simple using an instance of the CDbTableSchema class:

 echo 'Name: ', $tbl->name, ' (raw: ', $tbl->rawName, ')'; echo 'Fields: ', implode(', ', $tbl->columnNames); 

And so on. There are many methods and properties for this.
To get all the tables just use the CDbSchema class here.

The CDbSchema class has both the public tableNames property (an array of all tbl namnes) and the tables property containing all metadata. That is all, really.

To get to all of these instances, the following code should be sufficient:

 $connection = Yii::app()->db;//get connection $dbSchema = $connection->schema; //or $connection->getSchema(); $tables = $dbSchema->getTables();//returns array of tbl schema's foreach($tables as $tbl) { echo $tbl->rawName, ':<br/>', implode(', ', $tbl->columnNames), '<br/>'; } 

To create a drop-down list, you simply use the standard CHtml object:

 $options = array(); foreach($tables as $tbl) {//for example $options[$tbl->rawName] = $tbl->name; } $dropDown = CHtml::dropDownList('tables',$tables[0]->rawName, $options); 

Please spend some time reading the manual , all this is there. I did not use Yii , which is widespread, well, I did not use it at all, to be honest, but it took me only 5 minutes to fix it. Just look at the source. Each method / class / has a link to the exact line in the corresponding file!
Before asking others to figure out something for you, make some effort.

+16
source

select all column name from table:

 TableName::model()->getTableSchema()->getColumnNames(); 

It will return an array containing all the column names of the TableName.

+3
source

select all column name and its name:

 $fields=Tablename::model()->attributeLabels(); foreach($cont as $key=>$value){ echo "column name : ".$key." and lable ".$value; } 

it will display all field name and lable value from modal .....

0
source

Source: https://habr.com/ru/post/1500464/


All Articles