用PHP导出CSV文件

时间:2010-08-18 07:07:41

标签: php csv export

在使用PHP导出CSV文件时,有些记录不会包含在内。它似乎在转移时,即使仍有出口记录,它也会停止。有什么问题?

1 个答案:

答案 0 :(得分:0)

我在将CSV内容导出到数据库时遇到了一些错误。 大多数问题是因为数据库在保存记录时失败。 例如,你有这样的数据:

 "1;me;24"
 "2;you;"
 "3;they;26"
 "4;she;27"
 "5;it;28"

如果你的数据库有约束行不能为null,那么数据库会向php抛出错误。并且php将在记录到数据库的所有记录之前停止循环。

解决方案,您可以在代码中添加异常,当数据库无法插入数据库时​​,它将继续循环,直到将完成记录的csv发送到您的数据库。

<?php

error_reporting(E_ERROR);

class MySQLException extends Exception
{
    public function __construct($message,$code=0){                
        parent::__construct($message,$code);
    }
}

class Mysql
{    
    private $_DB_HOST;
    private $_DB_USERNAME;
    private $_DB_PASSWORD;
    private $_DB_NAME;
    private $_DB_SELECT_STATE;

    private $_CONNECTION;

    public function __construct($host, $username, $password, $dbname) {
        $this->_DB_HOST = $host;
        $this->_DB_USERNAME = $username;
        $this->_DB_PASSWORD = $password;
        $this->_DB_NAME = $dbname;

        $this->__connect();
        $this->__select_db();
    }

    private function __connect() {
        $this->_CONNECTION = mysql_connect($this->_DB_HOST, $this->_DB_USERNAME, $this->_DB_PASSWORD);

        if(!$this->_CONNECTION) {            
            throw new MySQLException('Could Not Connect to database with given setting');            
        }
    }

    private function __select_db() {
        $this->_DB_SELECT_STATE = mysql_select_db( $this->_DB_NAME , $this->_CONNECTION);

        if(!$this->_DB_SELECT_STATE) {
            throw new MySQLException('Could Not select to database with given setting');
        }
    }

    public function query($query){
        if( ( $result = mysql_query($query, $this->_CONNECTION )  )) {
            return $result;
        } else {
            $command = explode(' ', trim($query));
            throw new MySQLException('Could not do' . $command . ' query');
        }

    }
}


// connect to database
$database = new Mysql("localhost", "username", "password", "test");

// example your csv file before parsed
$csv = array("1;me;24", "2;you;", "3;they;26", "4;she;27", "5;it;28");

for($i = 0; $i < sizeof($csv); $i++){
    try{
        $row = explode(";", $csv[$i]);        
        $database->query("INSERT INTO testtable (id, name, age) VALUES (".$row[0].", '".$row[1]."', ".$row[2].")");
    } catch (MySQLException $e){
        echo 'We could not insert to the database <br>';
    }
}

如果你没有添加任何try catch,你的代码将在插入第二个查询时停止

"1;me;24"
"2;you;"
"3;they;26"
"4;she;27"
"5;it;28"

但是如果捕获异常,代码将保持循环直到结束解析。