You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

旧版Access(.mdb)中PDO无法用getColumnMeta,如何动态获取字段名

解决PDO Access驱动下动态获取字段名的问题

Got it, since PDOStatement::getColumnMeta() doesn't play nice with the Microsoft Access (*.mdb) ODBC driver, here are two solid approaches to dynamically grab column names even when you don't have prior knowledge of the SQL statement:

方法1:利用关联数组的键名(简单直接)

When you fetch rows with PDO::FETCH_ASSOC, the keys of the resulting array are exactly the column names (including aliases like sumvalue from your example). You can grab these keys from the first row of results, then proceed to collect all data:

$dbh = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\database.mdb;Uid=Admin");
// 示例SQL(实际场景中可以是任意未知SQL)
$sql = "SELECT name, SUM(b) AS sumvalue FROM table GROUP BY name";
$result = $dbh->query($sql);

$data = [];
$columnNames = [];

// 先获取第一行数据,同时提取字段名
if ($firstRow = $result->fetch(PDO::FETCH_ASSOC)) {
    $columnNames = array_keys($firstRow);
    $data[] = $firstRow;
    
    // 继续获取剩余行
    while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
        $data[] = $row;
    }
}

// 现在$columnNames包含所有字段名,$data是完整结果集

注意:如果结果集为空,这种方法无法获取字段名,适合你确定有返回数据的场景。

方法2:使用ODBC原生函数(支持空结果集)

Since you're using the ODBC driver under the hood, you can leverage native ODBC functions to get column metadata directly from the statement handle, even if no rows are returned:

$dbh = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\database.mdb;Uid=Admin");
$sql = "SELECT name, SUM(b) AS sumvalue FROM table GROUP BY name";

$stmt = $dbh->prepare($sql);
$stmt->execute();

// 获取底层ODBC结果集资源
$odbcResult = $stmt->getAttribute(PDO::ATTR_ODBC_RESULT);
$numColumns = odbc_num_fields($odbcResult);

$columnNames = [];
// 遍历所有字段(ODBC字段索引从1开始)
for ($i = 1; $i <= $numColumns; $i++) {
    $columnNames[] = odbc_field_name($odbcResult, $i);
}

// 之后可以正常获取数据
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

这种方法更灵活,即使SQL返回空结果,你依然能拿到字段名,不过它依赖ODBC函数的支持,只适用于ODBC驱动场景。

内容的提问来源于stack exchange,提问作者Clinton Lam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:29:04