當前位置: 首頁> 最新文章列表> 怎樣使用PDOStatement::columnCount函數準確獲取查詢結果的列數?

怎樣使用PDOStatement::columnCount函數準確獲取查詢結果的列數?

gitbox 2025-06-09

一、 PDOStatement::columnCount()是什麼?

PDOStatement::columnCount()PDOStatement對像中的一個方法,它返回與結果集中的列數相關的整數值。其原型如下:

 public PDOStatement::columnCount(): int

當你執行一條SQL 查詢之後(尤其是SELECT語句),你可以調用此方法來獲取結果集中包含多少列。


二、基本使用方法

來看一個最簡單的使用示例:

 <?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
$stmt = $pdo->query('SELECT id, name, email FROM users');

$columnCount = $stmt->columnCount();

echo "列數為: " . $columnCount;
?>

上述代碼執行完後將輸出:

 列數為: 3

這說明查詢結果中包含了三個字段: idnameemail


三、注意事項:必須執行查詢後才能獲取列數

一個常見的誤區是嘗試在查詢未執行或執行非結果集查詢(如INSERTUPDATEDELETE )後調用columnCount() 。這是不正確的做法:

 <?php
$stmt = $pdo->prepare('SELECT id, name FROM users WHERE id = :id');
// 未執行 -> columnCount 可能返回 0 或錯誤的值
echo $stmt->columnCount(); // 通常是 0
?>

為確保返回值準確,應始終在執行查詢並獲得結果集之後調用:

 $stmt->execute([':id' => 1]);
echo $stmt->columnCount(); // 正確返回列數

四、 columnCount()的典型應用場景

1. 動態構建表格標題

假設你正在構建一個通用的數據庫表瀏覽器工具,你需要根據查詢結果動態生成HTML 表格的標題行。可以使用columnCount()getColumnMeta()搭配完成:

 <?php
$stmt = $pdo->query('SELECT * FROM users');
$colCount = $stmt->columnCount();

echo "<table border='1'><tr>";
for ($i = 0; $i < $colCount; $i++) {
    $meta = $stmt->getColumnMeta($i);
    echo "<th>" . htmlspecialchars($meta['name']) . "</th>";
}
echo "</tr>";
?>

這將自動生成一個與查詢結果對應的表頭。


五、對比rowCount()columnCount()

很多初學者會混淆rowCount()columnCount() 。二者的區別如下:

  • columnCount() :獲取查詢結果中的列數。

  • rowCount() :獲取受影響的行數,但在SELECT查詢中並非總是可靠。

若要獲取SELECT查詢返回的行數,應該使用fetchAll()或遍歷結果集計數。


六、關於不同數據庫的兼容性

columnCount()的行為在各類數據庫中基本一致,但某些驅動(如舊版的SQLite 或某些ODBC 驅動)可能會在執行前返回0。因此,為獲得準確值,應遵循以下規則:

  1. 確保執行過execute()query()

  2. 使用支持元數據的驅動;

  3. 不要在無結果集的語句中調用此方法。


七、處理REST API 輸出字段信息

如果你在開發一個REST API,希望返回每條記錄的字段信息,可利用columnCount()自動生成字段列表,例如:

 <?php
$stmt = $pdo->query('SELECT * FROM users');
$columns = [];
for ($i = 0; $i < $stmt->columnCount(); $i++) {
    $meta = $stmt->getColumnMeta($i);
    $columns[] = $meta['name'];
}

header('Content-Type: application/json');
echo json_encode([
    'columns' => $columns,
    'data' => $stmt->fetchAll(PDO::FETCH_ASSOC)
]);
?>

這在構建類似https://gitbox.net/api/v1/table/users這樣的接口時尤為方便。