緩衝和非緩衝查詢可用於有限數量的記錄。
例如:使用緩衝方式實作 CSV 下載查詢時,超過 30,000 筆要緩衝的記錄時,就會出現記憶體限制問題。
同樣地,對於非緩衝查詢,負載會轉移到資料庫伺服器。
可以透過以下方式減少 Web 伺服器(緩衝)和 MySQL 伺服器(非緩衝)上的負載,以支援 30,000 筆以上記錄的 CSV 下載。
<?php
// Shell 命令。
$shellCommand = 'mysql '
. '--host='.escapeshellarg($hostname).' '
. '--user='.escapeshellarg($username).' '
. '--password='.escapeshellarg($password).' '
. '--database='.escapeshellarg($database).' '
. '--execute='.escapeshellarg($sql).' '
. '| sed -e \'s/"/""/g ; s/\t/","/g ; s/^/"/g ; s/$/"/g\'';
// CSV 標頭
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename={$csvFilename}");
header("Pragma: no-cache");
header("Expires: 0");
// 透過 shell 執行命令並以字串形式輸出完整結果
echo shell_exec($shellCommand);
?>
sed 正則表達式會消耗一些 CPU 資源。