我正在寻找一种方法来从使用PDO的SELECT查询返回的列索引中获取字段名称。我正在寻找的是等同于
mysql_field_name(resource $result, int $field_offset)
PHP文档说上面的函数从PHP 5.5.0开始被弃用,他们为PDO建议的替代方案被认为是实验性的,它的行为可能会在没有通知的情况下发生变化。这听起来不像我在申请中想要的东西。
我也不想查询MySQL系统表来获取列,因为这样效率不高。
如果fetchAll()函数的结果返回下面的结果数组,有没有办法可以通过指定列索引来检索列名的值(下面等于“NAME”)?
Array
(
[0] => Array
(
[NAME] => pear
[0] => pear
[COLOUR] => green
[1] => green
)
[1] => Array
(
[NAME] => watermelon
[0] => watermelon
[COLOUR] => pink
[1] => pink
)
)
答案 0 :(得分:1)
我想您可以使用array_flip($array)
来交换数组的键/值,然后就可以轻松获得“NAME”字段
此外,您可以使用fetch(PDO::FETCH_ASSOC)
检索数据,这样您只会获得查询的关联名称
答案 1 :(得分:0)
当我读到这个问题时,我觉得我是发布它的人,因为它正是我想要的,因为我想从使用pdo的查询中动态创建一个html表,我不想使用show tables或query架构,我想使用我的查询中的字段
hector给出的答案正是关键,我只是想我会分享/发布一个工作样本,我正在解析一个数组以获取我的表头,我正在创建和html表,其中包含查询的项目db:
$sqlselect = "SELECT name, last, othercol FROM persontable";
// I prepare and execute my query
$stmt = $conn->prepare($sqlselect);
$stmt->execute();
//get full recordset: header and records
$fullrs = $stmt->fetchAll(PDO::FETCH_ASSOC);
//get the first row (column headers) but do not go to next record
$colheaders = current($fullrs)
out = ""; //variable that will hold my table
out .= <table>;
//get my columns headers in the table
foreach($colheaders as $key=>$val)
{
$out .= '<th>'.$key.'</th>';
}
//get my records in the table
foreach($fullrs as $row)
{
$out .= "<tr>";
$out .= '<td>'.$row['name'].'</td>';
$out .= '<td>'.$row['last'].'</td>';
$out .= '<td>'.$row['othercol'].'</td>';
$out .= "<tr>";
}
out .= </table>;
//spit my table out
echo $out;
希望这有助于某人
答案 2 :(得分:0)
虽然不需要创建对象,但这对我有用。
<?php
namespace yourNameSpace;
// Extend PDO class for safe error handling
Class SafePDO extends \PDO {
public static function exception_handler($exception) {
// Output the exception details
die("Uncaught exception: " . $exception->getMessage());
}
public function __construct($dsn, $username='', $password='', $driver_options=array()) {
// Temporarily change the PHP exception handler while we . . .
set_exception_handler(array(__CLASS__, 'exception_handler'));
// . . . create a PDO object
parent::__construct($dsn, $username, $password, $driver_options);
// Change the exception handler back to whatever it was before
restore_exception_handler();
}
}
class TableRows extends \RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
trait traitSQLExecution {
private function generateTable(
$sql,
$servername = "default_value",
$username = "default_value",
$password = "default_value",
$dbname = "default_value"
) {
// Connect to the database with defined constants
$pdo = new SafePDO("mysql: host=$servername;dbname=$dbname", $username, $password);
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
try {
$stmt = $pdo->prepare($sql);
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(\PDO::FETCH_ASSOC);
$recordSet = $stmt->fetchAll();
echo '<table id="myReport"><tr>';
// Get table headers dynamically
foreach($recordSet[0] as $k=>$v) {
echo "<th>$k</th>";
}
echo '</tr>';
foreach(new TableRows(new \RecursiveArrayIterator($recordSet)) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
$pdo = null;
$stmt = null;
echo '</table>';
}
}
class obj_report {
// use section is used to include reusable pieces of code
use traitSQLExecution;
// Construct is called upon instantiation of an object
function __construct($table){
/****************************************************************************************
* Do not include public variables as this is bad design.
* Only public methods should be available to change the object in a predictable fashion.
****************************************************************************************/
if ( $table !== "" ) {
$this->generateTable($table);
}
}
}
$obj = new obj_report((string)htmlspecialchars($_POST['table']) ?: "");
$obj = NULL;
?>