0

I don't know why I cannot set the default fetch mode of PDO to FETCH_UNIQUE

Here is how I create the PDO object and make my request :

$PDO = new PDO($mysql,$login,$password);
$PDO->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_UNIQUE);

$prep = $PDO->prepare($selectQuery);
$prep->execute($params);

Then...

This is not working (it does not take into account the previous setAttribute()) :

$result = $prep->fetchAll(); 

This is working, but I don't want to have to write "PDO::FETH_UNIQUE" for every requests :

$result = $prep->fetchAll(PDO::FETCH_UNIQUE); 

What am I doing wrong ? My goal is to get the result array indexed by the primary key of the selected table, exactly like on this thread : Is there a way to fetch associative array grouped by the values of a specified column with PDO?

Community
  • 1
  • 1
flavienb
  • 3
  • 1
  • 4

1 Answers1

2
$PDO->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_UNIQUE);

This does not work because, PDO::FETCH_UNIQUE is not a valid constant for PDO::ATTR_DEFAULT_FETCH_MODE. See here the valid fetch mode constants http://www.php.net/manual/en/pdostatement.fetch.php

It seems that there is no way to enable PDO:FETCH_UNIQUE using $PDO->setAttribute(). You should pass it explicitly in the call to fetchAll().

Leonel Machava
  • 1,501
  • 11
  • 19
  • The clarify: `PDO::ATTR_DEFAULT_FETCH_MODE` sets the default fetch mode, not the default fetchAll mode. There's no way to set the default fetchAll mode. `PDO::FETCH_UNIQUE` is specific to `fetchAll()`. – deceze May 22 '14 at 09:19
  • Heck, it's a shame I'll have to write this for every request :( Anyway, thanks for the info... – flavienb May 22 '14 at 10:06
  • If you have to repeat your code you probably need to create a class to avoid that – David Vander Elst May 16 '18 at 20:36