Is it possible to set the default sampling mode of PDO?

Before I get 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 the default mode somewhere ....

Thank!

Edit I originally hoped that I could add PDO: FETCH_OBJ to the setAttribute code that I run when I connect to the database, but this does not seem to work ...

+62
php pdo
Oct 08 2018-10-10
source share
3 answers
 $connection = new PDO($connection_string); $connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); 
+114
Dec 08 '10 at 11:05
source share
 $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 ); 
+20
Jan 10 '13 at 8:55
source share

There are several ways to do this, but I do it the way I want. For MySQL with port 3306 in PDO. I am making $dsn line names. Now I am calling a new PDO with $db = new PDO(...) .

You need to use PDO::FETCH_OBJ when initializing the database connection, you can do it in various ways, but I made it a built-in array, as the fourth parameter of new PDO .

 $dsn = 'mysql:dbname=test;host=localhost;port=3306'; $username = 'root'; $password = ''; $db = new PDO($dsn, $username, $password, array ( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ )); 
0
Jun 09 '16 at 5:43
source share



All Articles