如何简单地返回 PDO 中的对象?

发布于 2024-07-16 10:10:45 字数 515 浏览 4 评论 0原文

第一次尝试PDO。

$dbh = new PDO("mysql:host=$hostname;dbname=animals", $username, $password);

$stmt = $dbh->query("SELECT * FROM animals");
$stmt->setFetchMode(PDO::FETCH_INTO, new animals);

foreach($stmt as $animals)
{
    echo $animals->name;
}

如果我跳过 setFetchMode() 方法,那么我需要调用我不想要的 $animals["name"]

但我不想为我所做的每个查询调用 setFetchMode()

有没有办法设置默认的 FetchMode ? 或者使用其他一些方法来使 query() 返回具有一个全局设置的对象。

Trying out PDO for the first time.

$dbh = new PDO("mysql:host=$hostname;dbname=animals", $username, $password);

$stmt = $dbh->query("SELECT * FROM animals");
$stmt->setFetchMode(PDO::FETCH_INTO, new animals);

foreach($stmt as $animals)
{
    echo $animals->name;
}

If i skip the setFetchMode() method, then I need to call $animals["name"] which I do not want.

But I do not want to call the setFetchMode() for each query I do.

Is there a way to set the default FetchMode ? Or some other method to make the query() return objects with one global setting.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

紫竹語嫣☆ 2024-07-23 10:10:45

也许您可以尝试扩展 PDO 类来自动为您调用该函数...简而言之:

class myPDO extends PDO
{
   function animalQuery($sql)
   {
     $result = parent::query($sql);
     $result->setFetchMode(PDO::FETCH_INTO, new animals);
     return $result;
   }

//   // useful if you have different classes
//   function vegetableQuery($sql)
//   {
//     $result = parent::query($sql);
//     $result->setFetchMode(PDO::FETCH_INTO, new vegetables);
//     return $result;
//   }
}

$dbh = new myPDO("mysql:host=$hostname;dbname=animals", $username, $password);

$stmt = $dbh->animalQuery("SELECT * FROM animals");

foreach($stmt as $animals)
{
    echo $animals->name;
}

Perhaps you could try extending the PDO class to automatically call the function for you... in brief:

class myPDO extends PDO
{
   function animalQuery($sql)
   {
     $result = parent::query($sql);
     $result->setFetchMode(PDO::FETCH_INTO, new animals);
     return $result;
   }

//   // useful if you have different classes
//   function vegetableQuery($sql)
//   {
//     $result = parent::query($sql);
//     $result->setFetchMode(PDO::FETCH_INTO, new vegetables);
//     return $result;
//   }
}

$dbh = new myPDO("mysql:host=$hostname;dbname=animals", $username, $password);

$stmt = $dbh->animalQuery("SELECT * FROM animals");

foreach($stmt as $animals)
{
    echo $animals->name;
}
七七 2024-07-23 10:10:45

由于 PDO 需要知道您想要获取哪个对象,因此您需要手动指定它。
但是,如果您只想使用对象而不是数组来检索数据,并且不关心它是否不是动物对象,那么当您在连接字符串之后设置属性时,默认情况下可以使用匿名对象,这可以在包装构造函数

  $connection = new PDO($connection_string);
  //PDO::FETCH_OBJ: returns an anonymous object with property names that correspond to the column names returned in your result set 
  $connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); 

然后所有查询都将返回对象。 虽然这并不完全是你想要的,但它很接近。


您还可以将数据注入到您的动物类中:

while($dataObj = ...) {
 $animal = new Animal($dataObj);
}

如果您查看查询函数,则可以通过传递额外参数来更改一些选项:
http://www.php.net/manual/en/pdo.query.php
我还没有测试过,但看起来它可以让你接近你想要的

Since PDO would need to know what object you want to fetch into, you would need to specify it manually.
But of you just want to use the object to retrieve the data rather than an array and do not care if its not an animal object, you can use anonymous objects by default when you set the attribute after the connection string which could be done in a wrapped constructor

  $connection = new PDO($connection_string);
  //PDO::FETCH_OBJ: returns an anonymous object with property names that correspond to the column names returned in your result set 
  $connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); 

Then all queries will return objects. Though it's not exactly what you want its close.


You could also inject the data into your animal class:

while($dataObj = ...) {
 $animal = new Animal($dataObj);
}

If you look at the query function it is possible to change some options by passing extra parameters:
http://www.php.net/manual/en/pdo.query.php
I haven't tested it but it looks like it gets you close to what you want

找个人就嫁了吧 2024-07-23 10:10:45

说到一般获取对象,PDO 有六种不同的模式来完成此任务。 我必须写一篇关于使用 PDO 获取对象的专门文章来列出所有对象。

关于您的具体问题,

如何简单地返回 PDO 中的对象?

只需使用 PDO::FETCH_OBJ 模式

有没有办法设置默认的FetchMode?

这取决于。
如果您关心的只是语法,并且您只想使用 $animal->name 而不是 $animal['name'],那么您可以要求 PDO默认情况下创建 stdClass() 实例。 为此,只需添加

PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ

PDO 连接选项 列表中(链接是我的另一个示例)写的,我强烈建议您检查一下,因为与 PDO 的连接是一项复杂的业务,它绝非您的示例中的一行)。

设置此选项后,您可以立即使用对象语法:

$stmt = $dbh->query("SELECT * FROM animals");
foreach($stmt as $animal)
{
    echo $animal->name;
}

如果您需要获取特定类,则对于对象列表,可以使用您当前的方法 setFetchMode() / foreach
或者您可以将 fetchAll() 与专用的 PDO::FETCH_CLASS 获取模式一起使用:

$herd = $pdo->query('SELECT name FROM animals')->fetchAll(PDO::FETCH_CLASS, 'Animal');

这就是您所能拥有的一切,只是因为您需要告诉 PDO,哪个特定的实例您将需要的课程。

还有其他选项,例如提供构造函数参数等。 您可以在上面链接的文章中查看它们。

Speaking of fetching objects in general, PDO has half a dozen different modes for this task. I had to write a dedicated article regarding fetching objects with PDO to list them all.

Regarding your particular questions,

How can I simply return objects in PDO?

Simply use the PDO::FETCH_OBJ mode

Is there a way to set the default FetchMode?

It depends.
If your concern is just a syntax, and you simply want to use $animal->name instead of $animal['name'], then you can ask PDO to create instances of stdClass() by default. To do so, just add

PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ

to the list of your PDO connection options (the link is to another example I wrote, which I highly recommend to check out, because connection to PDO is a complex business that is anything but a single line from your example).

Having this option set you can have your object syntax right away:

$stmt = $dbh->query("SELECT * FROM animals");
foreach($stmt as $animal)
{
    echo $animal->name;
}

While in case you need to fetch into a particular class, for a list of objects either use your current approach with setFetchMode() / foreach
or you can use fetchAll() with a dedicated PDO::FETCH_CLASS fetch mode:

$herd = $pdo->query('SELECT name FROM animals')->fetchAll(PDO::FETCH_CLASS, 'Animal');

This is all you can have, simply because you need to tell PDO, instances of which particular class you will need.

There are other options like providing constructor arguments and such. You can check them out in the article linked above.

旧城烟雨 2024-07-23 10:10:45

你可以尝试这样的方法:

$dbh = new PDO("mysql:host=$hostname;dbname=animals", $username, $password);

$stmt = $dbh->query("SELECT * FROM animals");
$stmt->setFetchMode(PDO::FETCH_CLASS, animals::class);

foreach($stmt as $animals)
{
    echo $animals->name;
}

You can try this way:

$dbh = new PDO("mysql:host=$hostname;dbname=animals", $username, $password);

$stmt = $dbh->query("SELECT * FROM animals");
$stmt->setFetchMode(PDO::FETCH_CLASS, animals::class);

foreach($stmt as $animals)
{
    echo $animals->name;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文