PHP/PDO:返回查询行而不使用 foreach?
我对此感到困惑,我运行一个查询,例如
foreach($dbh->query("SELECT * FROM ...") as $row) {
...do something with row()
但是当我 var_dump $dbh
它是一个 PDOstatement 对象。
这引出了两个问题:
- foreach 如何以某种方式将对象解析为单独的行?
- 如何将所有行存储在数组中,例如 $arr = $dbh->query(...)?这不起作用,因为它仍然是一个对象,
我当然可以在 foreach 下运行,并执行 $arr[] = $row,但这似乎有点愚蠢..
I am confused about this, I run a query such as
foreach($dbh->query("SELECT * FROM ...") as $row) {
...do something with row()
But when I var_dump $dbh
it is a PDOstatement object.
This leads me to two questions:
- How does foreach somehow resolve the object into separate rows?
- How can I store all rows in an array, like $arr = $dbh->query(...)? This does not work because it is still an object
I can of course run under the foreach, and do $arr[] = $row, but that seems a bit silly..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
PHP 有一些有趣的接口,可以让您将对象作为数组处理。在本例中,
PDOStatement
类实现了Traversable
,这允许在其上使用foreach
。请参阅此处 http://www.php.net/manual/en/class.pdostatement .php要将所有结果放入一个数组中,请查看 PDOStatement::fetchAll。如果将来遇到问题,请考虑查看 php.net 上的 PHP 文档。它包含示例和有用的用户评论。
PHP has some interesting interfaces that let you handle objects as arrays. In this case the
PDOStatement
class implementsTraversable
and this allows the use offoreach
on it. See here http://www.php.net/manual/en/class.pdostatement.phpTo get all your results in one array take a look at PDOStatement::fetchAll. And also in the future consider checking the PHP documentation on php.net if you run into problems. It's packed with examples and useful user comments.
使用
PDOStatement::fetchAll()
获取整个结果集作为数组。就 PDO 内部所做的而言,它使用迭代器来访问记录集的某种表示形式。通过这种方式,您可以使用更少的内存,因为您没有将整个结果集拉入 php,而是使用了类似于实现内部的资源
的内容。Use
PDOStatement::fetchAll()
to get the entire result set as array. AS far as what PDO does internally it uses an iterator to access some representation of a recordset. This way you use less memory because youre not pulling the entire result set into php, youre using something resembling aresource
thats internal to the implementation.