Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么我通过php/mysql生成的CSV文件上写有错误,而不是数据_Php_Mysql_Csv - Fatal编程技术网

为什么我通过php/mysql生成的CSV文件上写有错误,而不是数据

为什么我通过php/mysql生成的CSV文件上写有错误,而不是数据,php,mysql,csv,Php,Mysql,Csv,我一直在尝试通过我的一个sql表InnoDB创建CSV文件。当前,当我运行生成CSV的相应脚本时。它下载一个CSV文件,该文件的单元格上写有错误,如下所示: PHP警告:空行数据包正文 脚本: 生成CSV的函数: 更新:当表有超过10000条记录时会出现此错误,否则它可以正常工作。有人能告诉我为什么大量记录会出现这种情况吗?这里有一个我用来将数据提取到csv的小库,它在过去运行得非常好。它使用fputcsv,但需要PDO数据库连接,这可能是正常的,因为您使用的数据库连接已弃用。FetchTabl

我一直在尝试通过我的一个sql表InnoDB创建CSV文件。当前,当我运行生成CSV的相应脚本时。它下载一个CSV文件,该文件的单元格上写有错误,如下所示:

PHP警告:空行数据包正文

脚本:

生成CSV的函数:


更新:当表有超过10000条记录时会出现此错误,否则它可以正常工作。有人能告诉我为什么大量记录会出现这种情况吗?

这里有一个我用来将数据提取到csv的小库,它在过去运行得非常好。它使用fputcsv,但需要PDO数据库连接,这可能是正常的,因为您使用的数据库连接已弃用。FetchTable函数是一个实际构建csv并将其保存到磁盘的函数,从技术上讲,您可以复制该代码并将其修改为纯过程:

class   CSVtoZip
    {
        protected   $db;
        protected   $files;
        protected   $zipname;
        protected   $headerAddr;
        protected   $rootdir;

        public  function __construct($rootdir = '',$db)
            {
                $this->db       =   $db;
                $this->rootdir  =   $rootdir;
            }

        public  function FetchTable($table = false, $columns = array(), $filename = false, $db)
            {
                if($table !== false && $filename !== false && !empty($columns)) {

                        $filename   =   $this->rootdir.$filename.".csv";
                        $output     =   fopen($filename, 'w');
                        fputcsv($output, $columns);

                        $query      =   $this->db->prepare("select ".implode(",",$columns)." from $table");
                        $query->execute();

                        while($rows = $query->fetch(PDO::FETCH_ASSOC)) {
                                fputcsv($output, $rows);
                            }

                        $this->files[]  =   $filename;
                        fclose($output);
                    }
            }

        public  function Zipit($zipname = false)
            {
                if(isset($this->files) && !empty($this->files)) {
                        $this->zipname  =   ($zipname == false)? date("YmdHis").uniqid().".zip":$zipname;
                        $zipper         =   new ZipArchive();
                        $zipper->open($this->rootdir.$this->zipname, ZipArchive::CREATE);

                        foreach($this->files as $filelocation) {
                                $zipper->addFile(basename($filelocation));
                            }

                        $zipper->close();

                        foreach($this->files as $filelocation) {
                                unlink($filelocation);
                            }

                        $this->headerAddr   =   "Location: ".str_replace($_SERVER['DOCUMENT_ROOT'],"",$this->rootdir.$this->zipname);
                        $this->DownloadZip();
                        unlink($this->rootdir.$this->zipname);
                    }
            }

        protected   function DownloadZip()
            {
                if(isset($this->headerAddr)) {
                        header('Content-Type: text/csv; charset=utf-8');
                        header('Content-Disposition: attachment; filename='.basename($this->zipname));
                        header($this->headerAddr);
                    }
            }
    }

// Accepts a root directory and database connection (PDO)
$csv    =   new CSVtoZip($_SERVER['DOCUMENT_ROOT'].'/mydirectory/',$con);

// Fetch 'users' table and grab specific columns, name the file users.csv
$csv->FetchTable('users',array('ID','usergroup','first_name'),'users');

// Fetch another table with 2 columns, name it table2.csv
$csv->FetchTable('table2',array('ID','username'),'table2');

// Zip the file(s) into an archive called tester.zip, then download it 
$csv->Zipit('tester.zip');

这是一种表锁与行锁的对比,用于处理大量记录/缓冲区和更新

解决这个问题最简单的方法就是将其切换到InnoDB

在执行此操作之前锁定MyISAM表也可能会起作用,请尝试一下


编辑:我删除了,只要试着锁定它,这样当你转储它时,你是唯一一个访问它的人。

这实际上是一个mysql错误。是的,它是如何导致你知道的!!!有些人说我要检查表是否是myisam,因为这会导致错误。但是它已经是innodb了。为什么要手动创建CSV呢?你能给我一两个关于其他方法的提示吗
function exportMysqlToCsv($table,$filename = 'export.csv')
{
    $csv_terminated = "\n";
    $csv_separator = ",";
    $csv_enclosed = '"';
    $csv_escaped = "\\";
    $sql_query = "select * from $table";


// Gets the data from the database
$result = mysql_query($sql_query);
$fields_cnt = mysql_num_fields($result);


$schema_insert = '';

for ($i = 0; $i < $fields_cnt; $i++)
{
    $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
        stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
    $schema_insert .= $l;
    $schema_insert .= $csv_separator;
} // end for

$out = trim(substr($schema_insert, 0, -1));
$out .= $csv_terminated;

// Format the data
while ($row = mysql_fetch_array($result))
{
    $schema_insert = '';
    for ($j = 0; $j < $fields_cnt; $j++)
    {
        if ($row[$j] == '0' || $row[$j] != '')
        {

            if ($csv_enclosed == '')
            {
                $schema_insert .= $row[$j];
            } else
            {
                $schema_insert .= $csv_enclosed . 
                str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
            }
        } else
        {
            $schema_insert .= '';
        }

        if ($j < $fields_cnt - 1)
        {
            $schema_insert .= $csv_separator;
        }
    } 

    $out .= $schema_insert;
    $out .= $csv_terminated;
}

header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: " . strlen($out));
// Output to browser with appropriate mime type, you choose ;)
header("Content-type: text/x-csv");
//header("Content-type: text/csv");
//header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$filename");
echo $out;
exit;
}
class   CSVtoZip
    {
        protected   $db;
        protected   $files;
        protected   $zipname;
        protected   $headerAddr;
        protected   $rootdir;

        public  function __construct($rootdir = '',$db)
            {
                $this->db       =   $db;
                $this->rootdir  =   $rootdir;
            }

        public  function FetchTable($table = false, $columns = array(), $filename = false, $db)
            {
                if($table !== false && $filename !== false && !empty($columns)) {

                        $filename   =   $this->rootdir.$filename.".csv";
                        $output     =   fopen($filename, 'w');
                        fputcsv($output, $columns);

                        $query      =   $this->db->prepare("select ".implode(",",$columns)." from $table");
                        $query->execute();

                        while($rows = $query->fetch(PDO::FETCH_ASSOC)) {
                                fputcsv($output, $rows);
                            }

                        $this->files[]  =   $filename;
                        fclose($output);
                    }
            }

        public  function Zipit($zipname = false)
            {
                if(isset($this->files) && !empty($this->files)) {
                        $this->zipname  =   ($zipname == false)? date("YmdHis").uniqid().".zip":$zipname;
                        $zipper         =   new ZipArchive();
                        $zipper->open($this->rootdir.$this->zipname, ZipArchive::CREATE);

                        foreach($this->files as $filelocation) {
                                $zipper->addFile(basename($filelocation));
                            }

                        $zipper->close();

                        foreach($this->files as $filelocation) {
                                unlink($filelocation);
                            }

                        $this->headerAddr   =   "Location: ".str_replace($_SERVER['DOCUMENT_ROOT'],"",$this->rootdir.$this->zipname);
                        $this->DownloadZip();
                        unlink($this->rootdir.$this->zipname);
                    }
            }

        protected   function DownloadZip()
            {
                if(isset($this->headerAddr)) {
                        header('Content-Type: text/csv; charset=utf-8');
                        header('Content-Disposition: attachment; filename='.basename($this->zipname));
                        header($this->headerAddr);
                    }
            }
    }

// Accepts a root directory and database connection (PDO)
$csv    =   new CSVtoZip($_SERVER['DOCUMENT_ROOT'].'/mydirectory/',$con);

// Fetch 'users' table and grab specific columns, name the file users.csv
$csv->FetchTable('users',array('ID','usergroup','first_name'),'users');

// Fetch another table with 2 columns, name it table2.csv
$csv->FetchTable('table2',array('ID','username'),'table2');

// Zip the file(s) into an archive called tester.zip, then download it 
$csv->Zipit('tester.zip');