Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting column names in mssql pdo

I'm building an HTML table from some MS SQL PDO queries. Or trying to. The first roadblock I've hit is that I cannot get the column names of a particular table. Found here, I've tried to us the solution

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

got the error:

Fatal error: Using $this when not in object context

Whereas this (from the same SO post)

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

yielded the error:

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

I'm just trying to get the names of the columns so I can loop through and get the values of each of their rows. How can I accomplish this? Thanks

like image 463
1252748 Avatar asked Feb 11 '26 21:02

1252748


1 Answers

DESCRIBE is a MySQL specific command. On MS SQL you can use a strored procedure for that:

exec sp_columns MyTable

You'll find documentation at MSDN

Here comes a little example how this can be done using 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);
like image 77
hek2mgl Avatar answered Feb 13 '26 10:02

hek2mgl