PHP 在列表中存储 sql 查询时内存耗尽

PHP Memory Exhaustion when storing sql query in list

我想在列表中获取 SQL 查询的结果,但由于它有很多数据,因此会导致内存耗尽。

Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 20480 bytes)

这就是我尝试做的方式。有没有另一种方法不会导致内存耗尽?增加内存是没有选择的,因为会出现更大的数据集。

$sql = $pdoconnect->query('SELECT id FROM contacts');
$id_liste = $sql->fetchAll();

我已经用循环试过了,但还是一样:

while($row = $statement->fetch()){
    $id_liste[] = $row['id'];  }

使用发电机。这就是它们的设计目的。

像这样重写你的代码:

function fetchContacts()
{

   $result = $this->db->query('SELECT * FROM contacts');

   while($record = $result->fetch(PDO::FETCH_ASSOC)) {

       yield $record;

   }
}

// Then elsewhere in your code where you actually use the contacts:
foreach (fetchContacts() as $contact) {
    // All of your code here.
}

PHP 将只使用每个字段而不是每个记录所需的内存。应该可以。

此外,请尝试在 SQL 中使用 LIMIT,因为您可能不想一次处理所有 100,000 个联系人,对吗?