如何从PDOStatement获取列名?

时间:2012-05-29 12:22:00

标签: php mysql pdo

我最近构建了一个自动分页和查询结果排序的类,它与PDO一起使用。

以下是我从MySQL表中检索数据的方法:

$this->query = "SELECT _id, name, price, creationDate, isPublished FROM fruits";
$this->fetch_type = PDO::FETCH_ASSOC;
$this->result = $db->query($this->query);
$this->rows = $this->result->fetchAll($this->fetch_type);
$this->columns = empty($this->rows) ? array() : array_keys($this->rows[0]);

这样我可以轻松地将列名存储在数组中(这正是我需要的):

var_dump($this->columns):

array
  0 => string '_id' (length=3)
  1 => string 'name' (length=4)
  2 => string 'price' (length=5)
  3 => string 'creationDate' (length=12)
  4 => string 'isPublished' (length=11)

但是,如果获取类型为PDO::FETCH_OBJ,则我的方法不起作用,因为我不再使用2D数组,而是使用数组中的对象:

var_dump($this->rows):

array
 0 => 
object(stdClass)[11]
  public '_id' => string '1' (length=1)
  public 'name' => string 'apple' (length=5)
  public 'price' => string '26.00' (length=5)
  public 'creationDate' => string '0000-00-00 00:00:00' (length=19)
  public 'isPublished' => string '1' (length=1)
 1 => 
object(stdClass)[12]
  public '_id' => string '2' (length=1)
  public 'name' => string 'banana' (length=11)
  public 'price' => string '15.00' (length=5)
  public 'creationDate' => string '0000-00-00 00:00:00' (length=19)
  public 'isPublished' => string '1' (length=1)
 2 => 
object(stdClass)[13]
  public '_id' => string '3' (length=1)
  public 'name' => string 'orange' (length=6)
  public 'price' => string '12.12' (length=5)
  public 'creationDate' => string '0000-00-00 00:00:00' (length=19)
  public 'isPublished' => string '1' (length=1)

  etc...

那么,如何从上面的结果中获取列名呢?

2 个答案:

答案 0 :(得分:5)

对此的简单回答是castarray_keys()传递给显式(array)的项目 - 这样,数组不受影响,但对象变为正确的类型:

$this->columns = empty($this->rows) ? array() : array_keys((array) $this->rows[0]);

答案 1 :(得分:4)

getColumnMeta可以检索列的名称,它返回一个关联数组,其中包含明显的“名称”键。

所以

$meta = $this->result->getColumnMeta(0); // 0 indexed so 0 would be first column
$name = $meta['name'];