在mssql-pdo中获取列名


getting column names in mssql pdo

我正在从一些MS SQL PDO查询构建一个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); //this is the line that triggers the error
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 
    }         
}  
getColumnNames();

得到错误:

Fatal error: Using $this when not in object context

鉴于此(来自同一SO职位)

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

产生错误:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2812 General SQL Server error: Check messages from the SQL Server [2812] (severity 16) [(null)]'

我只是想得到列的名称,这样我就可以循环并得到它们每一行的值。我怎样才能做到这一点?感谢

DESCRIBE是MySQL特定的命令。在MS SQL上,您可以使用一个选通过程:

exec sp_columns MyTable

您可以在MSDN 上找到文档

下面是一个使用PDO:的小例子

<?php
// will contain the result value
$return = null;
// replace table name  by your table name
$table_name = 'table_name';
// prepare a statement
$statement = $pdo->prepare("exec sp_columns @table_name = :table_name");
// execute the statement with table_name as param
$statement->execute(array(
    'table_name' => $table_name
));
// fetch results
$result = $statement->fetchAll($sql);
// test output
var_dump($result);

这是一个老问题,但我还是要补充一下我学到的东西。通过这样做,我设法获得了列值。

try {
            $query = $this->db->prepare("DESCRIBE posts");
            $query->execute();
        //retrieve the columns inside the table posts
            $forumrows = $query->fetchAll(PDO::FETCH_COLUMN); 
            //var_dump($forumrows);
        //Output each column Id with its Value
            foreach($forumrows as $forumrow) {
                echo $forumrow . "</br>";
        }
          } catch(PDOException $e) {
                echo $e->getMessage();
        }