php 是否可以设置默认的 PDO 获取模式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3893858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:23:57  来源:igfitidea点击:

Is is possible to set a default PDO fetch mode?

phppdo

提问by Matt

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 setAttributecode I run when I connect to the DB, but that doesn't seem to work...

编辑。我最初希望我可以将 PDO:FETCH_OBJ 添加到我连接到数据库时运行的setAttribute代码中,但这似乎不起作用......

回答by Anon

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

回答by N'Kauh Nathan-Régis Bodje

$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 );