简体   繁体   English

MySQL PDO - 设置默认提取模式?

[英]MySQL PDO - Setting Default Fetch Mode?

So today, I'm finally making the transition from standard PHP MySQL functions to PDO. 所以今天,我终于从标准的PHP MySQL函数过渡到PDO了。 I noticed when fetching data as an object, we must run a line similar to the following: 我注意到在将数据作为对象提取时,我们必须运行类似于以下内容的行:

$STH = $DBH->query('SELECT name, addr, city from folks');
$STH->setFetchMode(PDO::FETCH_OBJ);

$result = $STH->fetch();

My question is regarding line 2. Is there a way to set this as the default behavior so that we don't need to set the fetch mode every single time we wish to run a query? 我的问题是关于第2行。有没有办法将其设置为默认行为,这样我们不需要每次希望运行查询时都设置获取模式? This seems pretty annoying to me. 这对我来说似乎很烦人。 Surely it's not necessary to do this? 当然没有必要这样做?

You can set the default fetch mode for the PDO object: 您可以为PDO对象设置默认提取模式:

$DBH->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);

This, of course, you do as soon as you've initialized your $DBH (PDO) object. 当然,这是在您初始化$ DBH(PDO)对象后立即执行的操作。

(For detailed documentation on this, see http://www.php.net/manual/de/pdo.setattribute.php ) (有关此的详细文档,请参阅http://www.php.net/manual/de/pdo.setattribute.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM