以下是完整的示例代码,其中代码中的step和nums有个疑问,假设总记录是从数据表查询的结果,该如何分次数?
下面代码中,nums以及step都是固定值,假设查询总记录是1563000,每次取1000或2000或以上,应该怎么计算step次数?
还是说我理解错误了?请各位指教,谢谢。
<?php
set_time_limit(0);
ini_set('memory_limit', '128M');
$fileName = date('YmdHis', time());
header('Content-Type: application/vnd.ms-execl');
header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');
$begin = microtime(true);
$fp = fopen('php://output', 'a');
$db = new mysqli('127.0.0.1', 'root', '', 'test');
if($db->connect_error) {
die('connect error');
}
$step = 100;
$nums = 10000;
$title = array('ID', '用户名', '用户年龄', '用户描述', '用户手机', '用户QQ', '用户邮箱', '用户地址');
foreach($title as $key => $item) {
$title[$key] = iconv('UTF-8', 'GBK', $item);
}
fputcsv($fp, $title);
for($s = 1; $s <= $step; ++$s) {
$start = ($s - 1) * $nums;
$result = $db->query("SELECT * FROM tb_users ORDER BY id LIMIT {$start},{$nums}");
if($result) {
while($row = $result->fetch_assoc()) {
foreach($row as $key => $item) {
$row[$key] = iconv('UTF-8', 'GBK', $item);
}
fputcsv($fp, $row);
}
$result->free();
ob_flush();
flush();
}
}
$end = microtime(true);
echo '用时:', $end - $begin;