我最近构建了一个用于自动分页和排序查询结果的类,它适用于 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)
但是,如果 fetch 类型为 ,我的方法不起作用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...
那么,如何从上述结果中获取列名?