以下代碼允許我將SQL語句傳遞給一個類,並調用其方法來顯示結果的好表,包括列名。當查詢返回沒有記錄時,如何通過PDO/Sqlite獲取列名?
但是,如果沒有結果,我仍然想顯示列名。
不幸的是,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>
但是您的查詢具有列名稱,PDO返回它們是否重要? – allen213
沒錯,但是如果我發送'SELECT *',那麼我需要依靠PDO從數據庫中獲取列名。 –
夠公平的,只是想知道你是不是正在想它 – allen213