簡體   English   中英

用PHP導出CSV文件

[英]Export CSV file in PHP

使用PHP導出CSV文件時,有些記錄將不包括在內。 似乎在傳輸時,即使仍有記錄要導出,它也停止了。 有什么問題?

將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"

但是如果您捕獲到異常,代碼將一直循環直到解析結束。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM