简体   繁体   中英

Select Column Names from SQL Server using PDO

I am attempting to select column names from a SQL Server database with the following code:

 public function getColumns($table){

        $columns = array();
        $sql = "select column_name from information_schema.columns where table_name = 'dbo.myTable'";

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

        try {

            if($stmt->execute()){

                $raw_column_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
                //
                //this is empty so we can stop right there
                //
                echo "<pre>";
                print_r($raw_column_data);
                echo "</pre>";



                }else{
                    echo "<pre>";
                    print_r($stmt->errorInfo());
                    echo "</pre>";
                }

                return $columns;

            } catch (Exception $e){

                    return $e->getMessage(); //return exception

            }
    }

Any ideas why the '$raw_column_data` array might be null? I have searched google high and low with no luck. I am almost positive that this is the correct syntax, and I am sure it is querying the database correctly.

Try removing the "dbo." in this line...

$sql = "select column_name from information_schema.columns where table_name = 'dbo.myTable'";

change to:

$sql = "select column_name from information_schema.columns where table_name = 'myTable'";

Your where statement looks wrong it shouldn't be where table_name = dbo.myTable

it should be

where 
    table_name = 'myTable' 
     and TABLE_SCHEMA = 'dbo'

One simple thing: Take that "dbo." out of the table name. That value will be found in the column "table_schema". So it should be "...where table_name='myTablel'"

Assuming all of your drivers are installed, and that you can get results from other queries, that would do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM