3

我正在从一些 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)]'

我只是想获取列的名称,这样我就可以遍历并获取它们每一行的值。我怎样才能做到这一点?谢谢

4

2 回答 2

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);
于 2013-02-05T03:18:14.953 回答
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();
        }
于 2016-04-27T12:29:46.317 回答