<?php
set_time_limit(0);
ini_set('memory_limit', '256M');

$fileName = date('YmdHis', time());

if(isset($_GET['mode'])){
    $mode = $_GET['mode'];
}else{
    $mode = 'down';
}
if($mode == 'down'){
    //流输出，直接下载生成得CSV文件时使用
    header('Content-Encoding: UTF-8');
    header("Content-type:application/vnd.ms-excel;charset=UTF-8");
    header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');
    //打开php标准输出流
    //以写入追加的方式打开
    $fp = fopen('php://output', 'a');//流输出 
}else{
    $fp = fopen("$fileName.csv", 'a');//保存到文件
}


//连接数据库
$dbhost = '47.105.110.22';
$dbuser = 'zb_kkk_gg';
$dbpwd = '3KMCC8DAhNTdLm6C';
$con = mysqli_connect($dbhost, $dbuser, $dbpwd);
if (mysqli_connect_errno()) {
   die('connect error');
}
//选择数据库
$database = 'zb_kkk_gg';
mysqli_select_db($con, $database);
//设置编码
mysqli_query($con, "set names UTF8");



//查询记录总条数
$sql = "SELECT count(id) as total FROM `zywd` where 1=1";
$result = mysqli_query($con,$sql);
$rs = mysqli_fetch_array($result);
$count = $rs['total'];
mysqli_free_result($result);

$nums = 500;//每次查询得记录数，根据服务器性能等实际情况调整大小
$step = $count / $nums;
$step = ceil($step);//根据每次查询记录数计算查询次数


/*
//设置标题
$title = array('ID','姓名','年龄','性别');
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 = mysqli_query($con,"SELECT * FROM `zywd` where 1=1 ORDER BY `id` LIMIT {$start},{$nums}");
    if($result) {
        while($row = mysqli_fetch_assoc($result)) {
            /*
            foreach($row as $key => $item) {
                //这里必须转码，不然会乱码
                $row[$key] = iconv("UTF-8", "GBK", $item);
            }
            */
            fputcsv($fp, $row);
        }
        mysqli_free_result($result); //释放结果集资源
        //每次查询完成刷新缓冲区
        ob_flush();
        flush();
    }
}
//断开连接
mysqli_close($con);
fclose($fp);
