PDOStatement :: getColumnMeta 不支持Microsoft Access驱动程序(* .mdb)。如何使用PDO动态获取字段名称?
注意: 我不会事先知道sql查询。 $ sql 以下仅供演示。
$dbh = new PDO("odbc:Driver={Microsoft Access Driver
(*.mdb)};Dbq=C:\database.mdb;Uid=Admin");
// Sample SQL could be used
$sql = "SELECT name, SUM(b) AS sumvalue FROM table GROUP BY name";
$result = $dbh->query($sql);
$data = [];
while ($row = $result->fetch()) {
for ($i = 0; $i < $result->columnCount(); $i++) {
$col = $result->getColumnMeta($i); //<------ This line not supported
$fieldName = $col['name'];
if (!isset($data[$fieldName])) $data[$fieldName] = [];
array_push($data[$fieldName], $row[$fieldName]);
}
}
// Get JSON result
echo json_encode($data);
答案 0 :(得分:0)
尝试类似的事情:
<?php
$fName = '';
$sumVal = '';
$pdoStr = 'odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\database.mdb;Uid=Admin"';
$dbh = new PDO($pdoStr);
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$sql = "SELECT name, SUM(b) AS sumvalue FROM table GROUP BY name";
$result = $dbh->query($sql);
$data = $result->fetchAll();
// here, you only have two fields, "name" and "sumvalue", so, you need to use these fields only, so this will work
foreach($data as $row) {
$fName = row['Name'];
$sumVal = row['sumvalue'];
// ...
}
?>
希望有所帮助!
和平!
答案 1 :(得分:0)
您无需使用getColumnMeta()
来获取列名称。如果您使用的是PDO::FETCH_ASSOC
,则列名将成为关联数组的键。你可以循环一下:
$results = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
$data = [];
foreach ($results as $row) {
foreach ($row as $key => $value) {
$data[$key][] = $value;
}
}
// Get JSON result
echo json_encode($data);
注意:您也可以将此设置为该连接的默认提取模式:
$dbh = new PDO("odbc:Driver={Microsoft Access Driver
(*.mdb)};Dbq=C:\database.mdb;Uid=Admin");
$dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
这样,您每次fetch()
/ fetchAll()
时都无需指定。