Is is possible to set a default PDO fetch mode?

PhpPdo

Php Problem Overview


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...

Php Solutions


Solution 1 - Php

$connection = new PDO($connection_string);
$connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);

Solution 2 - Php

$dsn = 'mysql:host='.$db_server.';dbname='.$db_name.';port='.$db_port;
$driver_options = array(
   PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'",
   PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
   PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
);               
$dbh = new PDO( $dsn, $db_user, $db_pass, $driver_options );

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMattView Question on Stackoverflow
Solution 1 - PhpAnonView Answer on Stackoverflow
Solution 2 - PhpN'Kauh Nathan-Régis BodjeView Answer on Stackoverflow