dongluo3962 2010-04-22 20:30
浏览 55
已采纳

如何使用pdo而不是大型数组从数据库中获取可迭代结果集?

I'm using PDO inside a database abstraction library function query that I've made.

I'm using fetchAll(), which if you have a lot of results, is supposed to get memory intensive, so I want to provide an argument to toggle between a fetchAll associative array and a pdo result set that can be iterated over with foreach and requires less memory (somehow).

I remember hearing about this, and I searched through the PDO docs, but I couldn't find any useful way to do that.

Does anyone know how to get an iterable resultset back from PDO instead of just a flat array? And am I right that using an iterable resultset will be easier on memory?

I'm using Postgresql, if it matters in this case.

.

.

.

The current query function is as follows, just for clarity.

/**
 * Running bound queries on the database.
 *
 * Use: query('select all from players limit :count', array('count'=>10));
 * Or: query('select all from players limit :count', array('count'=>array(10, PDO::PARAM_INT)));
**/
function query($sql_query, $bindings=array()){
 DatabaseConnection::getInstance();
 $statement = DatabaseConnection::$pdo->prepare($sql_query);
 foreach($bindings as $binding => $value){
  if(is_array($value)){
   $statement->bindParam($binding, $value[0], $value[1]);
  } else {
   $statement->bindValue($binding, $value);
  }
 }
 $statement->execute();
 // TODO: Return an iterable resultset here, and allow switching between array and iterable resultset.
 return $statement->fetchAll(PDO::FETCH_ASSOC); 
}
  • 写回答

1条回答 默认 最新

  • douxiaomang5640 2010-04-22 21:43
    关注

    Looks like I've found my solution in the form of the PDOStatement object itself, i.e. after doing a $statement->execute(); You can simply pass along the $statement object and foreach over that object. Can't use it as an array, but can do just about everything else with it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要