升级到PHP 5.4后,使用PDO将CSV文件导入数据库时​​出错

时间:2014-10-13 20:31:11

标签: php csv

我有一个php文件,可以将CSV文件导入我的数据库。由于我的托管服务提供商升级到PHP 5.4,我在“LINES TERMINATED BY”行上收到错误,但我不确定原因。这是我的代码:

<?php
    require('phpsqlajax_dbinfo.php');
    $databasehost = $db_host; 
    $databasename = $db_name; 
    $databasetable = "tbl_csvImport"; 
    $databaseusername=$db_user; 
    $databasepassword = $db_pass; 
    $fieldseparator = ","; 
    $lineseparator = "\n";
    $csvfile = "doecsv.csv";
    echo $lineseparator;
    if(!file_exists($csvfile)) {
        die("File not found. Make sure you specified the correct path.");
    }

    try {
        $pdo = new PDO("mysql:host=$databasehost;dbname=$databasename", 
            $databaseusername, $databasepassword,
            array(
                PDO::MYSQL_ATTR_LOCAL_INFILE => true,
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
            )
        );
    } catch (PDOException $e) {
        die("database connection failed: ".$e->getMessage());
    }

    $pdo->exec("DELETE FROM `$databasetable`");

    try {
        $affectedRows = $pdo->exec("
            LOAD DATA LOCAL INFILE ".preg_replace('/"[^"]+"/','',$pdo->quote($csvfile))." INTO TABLE `$databasetable`
            FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)."
            OPTIONALLY ENCLOSED BY ".$pdo->quote('"')."
            LINES TERMINATED BY ".$pdo->quote($lineseparator)."IGNORE 1 LINES");
    } catch (Exception $e) {
        die ("CSV Parse Failed: ".$e->getMessage()." | Error on line: ".$e->getLine());
    }

    echo" Success. <br/>";  
?>

错误代码:SQLSTATE [42000]:语法错误或访问冲突:1148此MySQL版本不允许使用命令在线错误:35

1 个答案:

答案 0 :(得分:0)

我找到了适用于我的解决方法:

http://crewow.com/CSV-Importer-in-MySQL.php