当查询没有返回记录时,如何通过PDO / Sqlite获取列名?

时间:2012-06-13 14:02:02

标签: php sqlite pdo

以下代码允许我将SQL语句传递给类并调用其方法以显示结果的漂亮表,包括列名。

但是,如果没有结果,我仍然希望显示列名

不幸的是,getColumnMeta没有像我在其他例子中那样返回任何数据。

有人知道如何让getColumnMeta()在这个例子中工作,或者当查询返回零行时,我可以从SQL语句中获取字段的名称吗?

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <style type="text/css">
            table thead tr td {
                background-color: #ddd;
                padding: 5px;
                font-weight: bold;
            }
            table tbody tr td {
                background-color: #eee;
                padding: 5px;
                color: navy;
            }
            div.sqlCommand {
                font-family: courier;
            }

            h2 {
                border-bottom: 1px solid #777;
            }
        </style>
    </head>
    <body>
        <?php

        $sql = 'SELECT LastName,FirstName,Title FROM employee WHERE 1=2 ORDER BY LastName';

        echo '<h2>sqlite</h2>';
        $dbSqlite = new DbSqlite($sql);
        echo $dbSqlite -> displayHtmlTable();

        class DbSqlite {
            protected $sql;
            protected $records = array();
            protected $columnNames = array();
            public function __construct($sql) {
                $this -> sql = $sql;
                $this -> initialize();
            }

            protected function initialize() {
                $db = new PDO('sqlite:chinook.sqlite');
                $result = $db -> query($this -> sql);
                $result -> setFetchMode(PDO::FETCH_ASSOC);
                $columnsAreDefined = false;
                while ($row = $result -> fetch()) {
                    $this -> records[] = $row;
                    if (!$columnsAreDefined) {
                        foreach ($row as $columnName => $dummy) {
                            $this -> columnNames[] = $columnName;
                        }
                        $columnsAreDefined = true;
                    }
                }

                if (count($this -> records) == 0) {
                    $total_column = $result -> columnCount();
                    var_dump($total_column);

                    for ($x = 0; $x < $total_column; $x++) {
                        $meta = $result -> getColumnMeta($x);
                        //var_dump($meta);
                        //bool(false)
                        //$column[] = $meta['name'];
                    }
                }
            }

            public function displayHtmlTable() {
                $r = '';

                $r .= '<div class="sqlCommand">' . $this -> sql . '</div>';

                $r .= '<table>';

                $r .= '<thead>';
                $r .= '<tr>';
                foreach ($this->columnNames as $columnName) {
                    $r .= '<td>' . $columnName . '</td>';
                }
                $r .= '</tr>';
                $r .= '</thead>';

                $r .= '<tbody>';
                foreach ($this->records as $record) {
                    $r .= '<tr>';
                    foreach ($record as $data) {
                        $r .= '<td>' . $data . '</td>';
                    }
                    $r .= '</tr>';
                }
                $r .= '</tbody>';
                $r .= '<table>';
                return $r;
            }

        }
        ?>
    </body>

</html>

3 个答案:

答案 0 :(得分:3)

元表sqlite_master包含所有信息。以下代码会将sqlite_master解析为列名$colnames

$colnames = array() ;

$stmt = $dbh->prepare("SELECT sql FROM sqlite_master WHERE tbl_name = 'put_table_name_here'") ;
$stmt->execute() ;
$row = $stmt->fetch() ;

$sql = $row[0] ;
$r = preg_match("/\(\s*(\S+)[^,)]*/", $sql, $m, PREG_OFFSET_CAPTURE) ;
while ($r) {
  array_push( $colnames, $m[1][0] ) ;
  $r = preg_match("/,\s*(\S+)[^,)]*/", $sql, $m, PREG_OFFSET_CAPTURE, $m[0][1] + strlen($m[0][0]) ) ;
}

答案 1 :(得分:2)

  1. 我会尝试第一种方法:
    • 运行查询
    • 检查是否有结果返回
    • 如果是,请运行您的initialize()displayHtmlTable
    • 如果,请运行将运行下一个查询的initializeEmptyResult()并填充$this->columnNames[]
  2. SELECT column_name FROM information_schema.columns WHERE table_name = 'my_table_name'
    

    查询依赖于MySQL bu应该有更多其他数据库的替代方案,或者仍然可以运行DESCRIBE table并从结果中解析列名称(应该是SQL DBMS不依赖)。

    1. 第二,我认为更容易实现:如果查询没有返回结果,请不要显示库存名称或表格,只显示一条消息:&#39;未找到结果。 #39 ;.这可以在您的displayHtmlTable方法中实现:

          public function displayHtmlTable() {
              $r = '';
      
              $r .= '<div class="sqlCommand">' . $this -> sql . '</div>';
      
              if(count($this->records) > 0) {
                  $r .= '<table>';
      
                  $r .= '<thead>';
                  $r .= '<tr>';
                  foreach ($this->columnNames as $columnName) {
                      $r .= '<td>' . $columnName . '</td>';
                  }
                  $r .= '</tr>';
                  $r .= '</thead>';
      
                  $r .= '<tbody>';
                  foreach ($this->records as $record) {
                      $r .= '<tr>';
                      foreach ($record as $data) {
                          $r .= '<td>' . $data . '</td>';
                      }
                      $r .= '</tr>';
                  }
                  $r .= '</tbody>';
                  $r .= '<table>';
              } else {
                  $r .= '<div class="no-results">No results found for query.</div>';
              }
      
              return $r;
          }
      
    2. 而且您不必费心使用列名......

      编辑:对于第一个案例,发现SQLite的查询应该与select * from information_schema.columns where table_name = 'xxx'相同:

      PRAGMA table_info(table-name);
      

答案 2 :(得分:0)

只是为了扩展@shadyyx评论:

  

PRAGMA table_info(table-name);

我没有方便的PDO_SQLITE沙箱,但使用原生SQLite3驱动程序,此代码段将为您提供 $ arrColumns 中表 table-name 的列名称:

$db = new SQLite3('db.sqlite');
$db->query('PRAGMA table_info(table-name)');
while ($col = $res->fetchArray(SQLITE3_ASSOC)) {
    $arrColnames[]=$col['name'];
}
print_r($arrColnames);