哈哈,这也发生在我身上!和I've complained 给开发者,他们ignored me。
当你调用 result() 时,它会遍历每一个可能的结果,并将记录存储到一个巨大的内部数组中。在 result_object() 和 result_array() 的末尾查看system/database/DB_result.php while 循环
修复它的三种方法。
简单的方法:
LIMIT(或TOP in MSSQL)您在 SQL 查询中的结果。
SELECT TOP(100) * FROM Table
UPDATED 无缓冲方式:
使用 unbuffered_row() 函数,该函数是在提出此问题 2 年后的 introduced。
$query = $this->db->query($sql);
// not $query->result() because that loads everything into an internal array.
// and not $query->first_row() because it does the same thing (as of 2013-04-02)
while ($record = $query->unbuffered_row('array')) {
// code...
}
艰难的道路:
使用 proper 结果对象,该对象使用 PHP5 迭代器(开发人员不喜欢它,因为它不包括 php4)。在您的 DB_result.php 文件中添加类似这样的内容:
-class CI_DB_result {
+class CI_DB_result implements Iterator {
var $conn_id = NULL;
var $result_id = NULL;
var $result_array = array();
var $result_object = array();
- var $current_row = 0;
+ var $current_row = -1;
var $num_rows = 0;
var $row_data = NULL;
+ var $valid = FALSE;
/**
function _fetch_assoc() { return array(); }
function _fetch_object() { return array(); }
+ /**
+ * Iterator implemented functions
+ * http://us2.php.net/manual/en/class.iterator.php
+ */
+
+ /**
+ * Rewind the database back to the first record
+ *
+ */
+ function rewind()
+ {
+ if ($this->result_id !== FALSE AND $this->num_rows() != 0) {
+ $this->_data_seek(0);
+ $this->valid = TRUE;
+ $this->current_row = -1;
+ }
+ }
+
+ /**
+ * Return the current row record.
+ *
+ */
+ function current()
+ {
+ if ($this->current_row == -1) {
+ $this->next();
+ }
+ return $this->row_data;
+ }
+
+ /**
+ * The current row number from the result
+ *
+ */
+ function key()
+ {
+ return $this->current_row;
+ }
+
+ /**
+ * Go to the next result.
+ *
+ */
+ function next()
+ {
+ $this->row_data = $this->_fetch_object();
+ if ($this->row_data) {
+ $this->current_row++;
+ if (!$this->valid)
+ $this->valid = TRUE;
+ return TRUE;
+ } else {
+ $this->valid = FALSE;
+ return FALSE;
+ }
+ }
+
+ /**
+ * Is the current_row really a record?
+ *
+ */
+ function valid()
+ {
+ return $this->valid;
+ }
+
}
// END DB_result class
然后使用它,而不是调用$query->result(),您只使用末尾没有->result() 的对象,如$query。并且所有内部 CI 内容仍然适用于 result()。
$query = $this->db->query($sql);
foreach ($query as $record) { // not $query->result() because that loads everything into an internal array.
// code...
}
顺便说一句,我的迭代器代码与他们的代码一起使用整个 -1 的东西有一些逻辑问题,所以不要在同一个对象上同时使用 $query->result() 和 $query。如果有人想解决这个问题,你很棒。