我遇到了内存限制错误,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 但我不想要这个解决方案。