How to get the column names of table in a database

2019-04-03 00:49发布

问题:

I am creating an app in zend where the user will enter the host, database name, username and password to connect the database and will able to retrieve the tables and columns in the tables also to start some work..

I am using this code to get the tables in a database:

$ExternalDb = new Zend_Db_Adapter_Pdo_Mysql(array(
    'host'     => $host,
    'username' => $user,
    'password' => $pass,
    'dbname'   => $dbName
));

try{
    //Create connection
    echo $ExternalDb->getConnection()->getAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY);

    foreach($ExternalDb->listTables() as $table){

      //$table = new $table(array('db' => $ExternalDb)); it doesn't work
        echo "<pre>";
        print_r($table);
      //$cols = $table->info(Zend_Db_Table_Abstract::COLS); It doesn't work
        echo "</pre>";

    }

} catch (Exception $ex) {
    echo $ex;
}

I am able to get the table names but I am trying to get the column names also...

Thanks in advance!

回答1:

You can retrieve information from Zend_Db_Table_Abstract.

Create a new class like this:

class foo extends Zend_Db_Table_Abstract
{
}

In your code:

foreach($ExternalDb->listTables() as $table){
    $dbTable = new foo($ExternalDb);            
    $dbTable->setOptions(array($dbTable::NAME => $table));
    var_dump($dbTable->info($dbTable::COLS));
    unset($dbTable);
}


回答2:

Another way without Zend_Db_Table_Abstract, directly with Zend_Db_Adapter, you can use describeTable() method:

foreach($ExternalDb->listTables() as $table){    
    $describ = $ExternalDb->describeTable($table);
    foreach($describ as $col_name => $col_desc){
        var_dump($col_name);
    }
}