php pdo:获取表的列名

时间:2011-03-25 03:34:13

标签: php pdo fetch

如何使用PDO从表中获取所有列名?

id         name        age
1          Alan        35      
2          Alex        52
3          Amy         15

我想要的信息是,

id         name        age

修改

这是我的尝试,

$db = $connection->get_connection();
$select = $db->query('SELECT * FROM contacts');

$total_column = $select->columnCount();
var_dump($total_column);

for ($counter = 0; $counter < $total_column; $counter ++) {
    $meta = $select->getColumnMeta($counter);
    $column[] = $meta['name'];
}
print_r($column);

然后我明白了,

Array
(
    [0] => id
    [1] => name
    [2] => age
    ...

)

13 个答案:

答案 0 :(得分:89)

我通过以下方式解决问题(仅限MySQL)

$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);

答案 1 :(得分:31)

这适用于MySQL,Postgres以及可能使用LIMIT子句的任何其他PDO驱动程序。

添加注意LIMIT 0以提高性能:

$rs = $db->query('SELECT * FROM my_table LIMIT 0');
for ($i = 0; $i < $rs->columnCount(); $i++) {
    $col = $rs->getColumnMeta($i);
    $columns[] = $col['name'];
}
print_r($columns);

答案 2 :(得分:21)

我的2美分:

$result = $db->query('select * from table limit 1');
$fields = array_keys($result->fetch(PDO::FETCH_ASSOC));

您将在var $ fields中将列名称作为数组。

答案 3 :(得分:10)

  

$ sql =“从中选择column_name   information_schema.columns在哪里   table_name ='myTable'“;

PHP函数 学分:http://www.sitepoint.com/forums/php-application-design-147/get-pdo-column-name-easy-way-559336.html

    function getColumnNames(){ 

    $sql = "select column_name from information_schema.columns where table_name = 'myTable'";
    #$sql = 'SHOW COLUMNS FROM ' . $this->table; 

    $stmt = $this->connection->prepare($sql); 

    try {     
        if($stmt->execute()){ 
            $raw_column_data = $stmt->fetchAll(PDO::FETCH_ASSOC); 

            foreach($raw_column_data as $outer_key => $array){ 
                foreach($array as $inner_key => $value){ 
                            if (!(int)$inner_key){ 
                                $this->column_names[] = $value; 
                            } 
                } 
            } 
            } 
            return $this->column_names; 
        } catch (Exception $e){ 
                return $e->getMessage(); //return exception 
        }         
    }  

答案 4 :(得分:3)

这是我使用的功能。基于@Lauer回答以及其他一些资源创建:

//Get Columns
function getColumns($tablenames) {
global $hostname , $dbnames, $username, $password;
try {
$condb = new PDO("mysql:host=$hostname;dbname=$dbnames", $username, $password);

//debug connection
$condb->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$condb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// get column names
$query = $condb->prepare("DESCRIBE $tablenames");
$query->execute();
$table_names = $query->fetchAll(PDO::FETCH_COLUMN);
return $table_names;

//Close connection
$condb = null;

} catch(PDOExcepetion $e) {
echo $e->getMessage();
}
}

用法示例:

$columns = getColumns('name_of_table'); // OR getColumns($name_of_table); if you are using variable.

foreach($columns as $col) {
echo $col . '<br/>';
}

答案 5 :(得分:2)

这是一个老问题,但这是我的输入

function getColumns($dbhandle, $tableName) {
    $columnsquery = $dbhandle->query("PRAGMA table_info($tableName)");
    $columns = array();
    foreach ($columnsquery as $k) {
        $columns[] = $k['name'];
    }
    return $columns;
}

只需将您的变量放入pdo对象和tablename即可。适合我

答案 6 :(得分:1)

PDOStatement::getColumnMeta()

正如Charle所提到的,这是一个语句方法,这意味着它从准备好的语句(查询)中提取列数据。

答案 7 :(得分:1)

这种方法适用于SQLite和MySQL。它可能与其他人合作,请让我知道你的经历。

  • 如果存在行,则工作
  • 如果不存在任何行,则使用(使用DELETE FROM table测试)

代码:

$calendarDatabase = new \PDO('sqlite:calendar-of-tasks.db');    
$statement = $calendarDatabase->query('SELECT *, COUNT(*) FROM data LIMIT 1');
$columns = array_keys($statement->fetch(PDO::FETCH_ASSOC));
array_pop($columns);
var_dump($columns);

我不保证这是每个ANSI或其他的有效SQL,但它适用于我。

答案 8 :(得分:0)

这是SQLite3的一个非常有用的解决方案。因为OP没有具体指明MySQL,并且尝试在SQLite上使用某些解决方案失败。

    $table_name = 'content_containers';
    $container_result = $connect->query("PRAGMA table_info(" . $table_name . ")");
    $container_result->setFetchMode(PDO::FETCH_ASSOC);


    foreach ($container_result as $conkey => $convalue)
    {

        $elements[$convalue['name']] = $convalue['name'];

    }

这将返回一个数组。由于这是一个直接的信息转储,您需要迭代并过滤结果以获得如下内容:

Array
(
    [ccid] => ccid
    [administration_title] => administration_title
    [content_type_id] => content_type_id
    [author_id] => author_id
    [date_created] => date_created
    [language_id] => language_id
    [publish_date] => publish_date
    [status] => status
    [relationship_ccid] => relationship_ccid
    [url_alias] => url_alias
)

当表为空时,这是特别好的。

答案 9 :(得分:0)

我对SQLite的贡献

/**
 * Returns an array of column names for a given table.
 * Arg. $dsn should be replaced by $this->dsn in a class definition.
 *
 * @param string $dsn Database connection string, 
 * e.g.'sqlite:/home/user3/db/mydb.sq3'
 * @param string $table The name of the table
 * 
 * @return string[] An array of table names
 */
public function getTableColumns($dsn, $table) {
   $dbh = new \PDO($dsn);
   return $dbh->query('PRAGMA table_info(`'.$table.'`)')->fetchAll(\PDO::FETCH_COLUMN, 1);
}

答案 10 :(得分:-1)

只需输入您的数据库名称,用户名,密码(我标记的位置?)和表名称。&amp; Yuuppiii!....您从主数据库获取所有数据(列名称)

<?php 

function qry($q){

    global $qry;
    try {   
    $host = "?";
    $dbname = "?";
    $username = "?";
    $password = "?";
    $dbcon = new PDO("mysql:host=$host; 
    dbname=$dbname","$username","$password");
}
catch (Exception $e) {

    echo "ERROR ".$e->getMEssage();

}

    $qry = $dbcon->query($q);
    $qry->setFetchMode(PDO:: FETCH_OBJ);

    return $qry;

}


echo "<table>";

/*Get Colums Names in table row */
$columns = array();

$qry1= qry("SHOW COLUMNS FROM Your_table_name");

while (@$column = $qry1->fetch()->Field) {
    echo "<td>".$column."</td>";
    $columns[] = $column;

}

echo "<tr>";

/ *将所有数据提取到html表* /

$qry2 = qry("SELECT * FROM Your_table_name");

while ( $details = $qry2->fetch()) {

    echo "<tr>";
    foreach ($columns as $c_name) {
    echo "<td>".$details->$c_name."</td>";

}

}

echo "</table>";

?>

答案 11 :(得分:-1)

$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);

必须

$q = $dbh->prepare("DESCRIBE database.table");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);

答案 12 :(得分:-5)

没有必要进行二次查询,这是愚蠢的。只需使用内置的oci_field_name()函数:

以下是一个例子:

oci_execute($stid);                  //This executes

    echo "<table border='1'>\n";
    $ncols = oci_num_fields($stid);
    echo "<tr>";
    for ($i = 1; $i <= $ncols; $i++) {
            $column_name  = oci_field_name($stid, $i);
            echo "<td>$column_name</td>";
    }
    echo "</tr>";


    while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
            echo "<tr>\n";
            foreach ($row as $item) {
                    echo "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
            }
            echo "</tr>\n";
    }
    echo "</table>\n";