在mssql pdo中获取列名

时间:2013-02-05 03:15:23

标签: php sql-server pdo

我正在从一些MS SQL PDO查询构建HTML表。或试图。我遇到的第一个障碍是我无法获取特定表的列名。找到here,我尝试了解决方案

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)]'

我只是想获取列的名称,以便我可以遍历并获取每行的值。我怎么能做到这一点?感谢

2 个答案:

答案 0 :(得分:3)

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);

答案 1 :(得分:0)

这是一个老问题,但我会添加我所学到的东西。我设法通过这样做获得了列值。

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();
        }