2014-02-24 41 views
2

如何獲取yii中的所有表名?獲取yii中的所有表名

mySQL中的sql查詢是SHOW TABLES。 我想:

$sql = 'SHOW TABLES'; 
$tables = Yii::app()->db 
     ->createCommand($sql) 
     ->queryAll(); 
print_r($tables); 

它拋出一個錯誤:

CDbCommand failed to execute the SQL statement: 
CDbCommand failed to prepare the SQL statement: 
SQLSTATE[HY000]: General error: 1 near "SHOW": syntax error. 
The SQL statement executed was: SHOW TABLES 

回答

6

試試這個:

$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/>'; 
} 

參見:How to get all table and column names from database in Yii Framework

3

如果你想使用警予然後瑪尼的答案是正確的。如果你想使用create命令,然後拿到表名,你可以使用

$sql='SELECT * FROM INFORMATION_SCHEMA.TABLES' 
$tables = Yii::app()->db 
     ->createCommand($sql) 
     ->queryAll(); 
相關問題