I’ve recently built a class for automatic paging and ordering of query results, that works with PDO.
Here’s how I retrieve the data from a MySQL table:
$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]);
This way I can easily store the column names inside an array (that’s exactly what I need):
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)
However, my method doesn’t work if the fetch type is PDO::FETCH_OBJ, since I’m no more working with 2D arrays, but with objects inside arrays:
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...
So, how can I get column names from a result like this above?
The simple answer to this is to cast the item that you pass to
array_keys()to an explicit(array)– that way, arrays are unaffected but objects become the correct type: