【问题标题】:replace fetchAll by fetch to avoid memory limit将 fetchAll 替换为 fetch 以避免内存限制
【发布时间】:2012-09-09 13:35:07
【问题描述】:

我在使用fetchAll 时遇到了内存限制错误,因此我尝试使用fetch,但我找不到解决方法。有什么建议吗?在哪里/如何使用 while 而不是 foreach

这里是原始代码:

// We get all the data from the table
$Qselect = $pdo->prepare('SELECT * FROM '.$table_to_export.''); 
$Qselect->execute(array(''));
$results = $Qselect->fetchAll(PDO::FETCH_ASSOC); // Here is the problem
$countRmain = $Qselect->rowCount();

// We get the column names
$Qdescribe = $pdo->prepare('DESCRIBE '.$table_to_export.'');
$Qdescribe->execute();
$limit = $Qdescribe->rowCount()-1;      // Number of column in the table
$table_fields = $Qdescribe->fetchAll(PDO::FETCH_COLUMN); // No problem here

foreach($table_fields as $key => $fields){
    $outputCsv .= trim($fields).';';
}

// We remove the ; at the end
$outputCsv = rtrim($outputCsv, ';');

// Data
$outputCsv .= "\n";
if($countRmain > 0){
    foreach($results as $row){
            $column = 0 ;
        foreach ($row as $key => $val){         
            if (is_null($val)){
                $outputCsv .= 'NULL;';  // If the field id empty, we add NULL
            }
            else {
                $outputCsv .= $val.';'; // We add the value in the file
            }
            if ($column == $limit)
                $outputCsv .= "\n";
            $column ++;
        }
    }
}
    else
        exit('No data to export');

我尝试将 foreach 循环包含到 while($results = $Qselect->fetch()){ 中,但这需要很长时间(50000 行需要 10 分钟)

PS:如果我增加 PHP memory_limit 它适用于 fetchAll 但我不想要这个解决方案。

【问题讨论】:

    标签: php mysql foreach fetch fetchall


    【解决方案1】:

    试试这个。

    1. comment line 4
    2. Replace line 23:
        while($row = $Qselect->fetch(PDO::FETCH_ASSOC)){
    3. Skip (or Replace) checks on line 22
    

    想法很简单:你之前得到了$result,但没有加载整个数组。您只需一步一步加载记录。即使对于 1M 行,这也不够慢,因为您将一个代码迭代循环替换为另一个 same 代码迭代。
    如果您仍然遇到时间问题,请尝试重新组织\优化您的代码。

    【讨论】:

      【解决方案2】:

      我也遇到过这个问题。

      增加以下变量,使您的页面执行不会停止:

      max_input_time
      memory_limit
      max_execution_time
      

      或者你可以使用

      while($row = $Qselect->fetch(PDO::FETCH_ASSOC)){
      

      代替fatchAll

      【讨论】:

      • @remyremy。它是你的选择,你可以选择任何一个。如上所述,增加变量或使用 fetch。但是你还需要在使用 fetch 时优化代码。
      • 更多的人从他们自己的 wamp 服务器上使用它,所以我不想长期选择这个解决方案。我没有投反对票,但我猜有人这样做了,因为在我的原始消息中我提到我不想更改内存限制。不管怎么说,还是要谢谢你。我会尽快尝试 StasGrin 回答并优化代码。
      猜你喜欢
      • 2019-06-28
      • 1970-01-01
      • 2013-04-19
      • 1970-01-01
      • 2011-12-04
      • 2023-02-24
      • 1970-01-01
      • 1970-01-01
      • 2014-08-26
      相关资源
      最近更新 更多