75

Before I retrieve data I always have to type:

$STH->setFetchMode(PDO::FETCH_OBJ);

In the interest of making my code more readable it would be great if I could set a default mode somewhere....

Thanks!

Edit. I was originally hoping I could add PDO:FETCH_OBJ to the setAttribute code I run when I connect to the DB, but that doesn't seem to work...

Handsome Nerd
  • 17,114
  • 22
  • 95
  • 173
Matt
  • 7,022
  • 16
  • 53
  • 66

2 Answers2

149
$connection = new PDO($connection_string);
$connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
Anon
  • 1,506
  • 1
  • 11
  • 3
32
$dsn = "mysql:host=$db_server;dbname=$db_name;port=$db_port;charset=utf8mb4";
$driver_options = [
   PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
   PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
];               
$dbh = new PDO( $dsn, $db_user, $db_pass, $driver_options );
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • Thanks for posting an answer! While a code snippet could answer the question it's still great to add some addition information around, like explain, etc .. – j0k Jan 10 '13 at 09:11
  • Yes of course ! Just to add that PDO allow to set a list of parameter. So using the array $options you can easily add more input to customise you Query output ... – N'Kauh Nathan-Régis Bodje Jan 10 '13 at 09:44
  • This looks great as it is at this point in time. Also it works for PDO::FETCH_NAME and PDO::FETCH_ASSOC ,... etc. – BradChesney79 Nov 18 '20 at 20:57