PDOStatement: Getting different results between `fetchAll($mode);` and `setFetchMode($mode); fetchAll();`

Viewed 2205

I have a question regarding PDO.

Is there a difference between

$sql = "SELECT * FROM pages";
$pdo = $this->db->query($sql);
$result = $pdo->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC); 

and

$sql = "SELECT * FROM pages";
$pdo = $this->db->query($sql);
$pdo->setFetchMode(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);
$result = $pdo->fetchAll();

?

I get a different $result for each of them.

The documentation from PHP about these fetch modes is not very clear to me.

I have a table with different pages, and I want to fetch all the pages indexed by their ID.

The first method returns this:

[
   [id of page 1] => [
      [0] => [ page 1 ],
   ],
   [id of page 2] => [
      [0] => [ page 2 ],
   ],
   ...
]

When I do the second method, I only get:

[
   [0] => [ page 1 ],
   [1] => [ page 2 ],
   [3] => [ page 3 ],
   ...
]

I want it like this:

[
   [id of page 1] => [ page 1 ],
   [id of page 2] => [ page 2 ],
   [id of page 3] => [ page 3 ],
   ...
]

The first one is good enough for me because I can easily tweak it with the array map function:

array_map('reset', $result);
1 Answers
Related