开发者

PHP/PDO: return query rows without foreach?

开发者 https://www.devze.com 2023-01-19 15:30 出处:网络
I am confused about this, I run a query such as foreach($dbh->query(\"SELECT * FROM ...\") as $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 s开发者_JAVA百科illy..


  1. PHP has some interesting interfaces that let you handle objects as arrays. In this case the PDOStatement class implements Traversable and this allows the use of foreach on it. See here http://www.php.net/manual/en/class.pdostatement.php

  2. To 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.


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 a resource thats internal to the implementation.

0

精彩评论

暂无评论...
验证码 换一张
取 消