PHP script to import csv data into mysql

前端 未结 4 608
囚心锁ツ
囚心锁ツ 2020-12-23 11:03

I have tried the following code but getting some errors. Here I can read the input file but I am getting the following error:Deprecated: Function split() is deprecated in C:

4条回答
  •  别那么骄傲
    2020-12-23 11:16

    Several tips:

    • Don't use the deprecated ext/mysql, when you can use ext/mysqli or PDO.

    • Don't read the entire csv file into a PHP variable. What happens when the file is 500MB?

    • Don't write custom PHP code to parse csv data, when you can use the builtin function fgetcsv().

    • Don't create a new SQL statement for every row in the data, when you can use prepared statements.

    • Don't interpolate data from an external file into SQL statements. This risks SQL injection vulnerabilities, just like when you interpolate untrusted user input.

    • Don't parse and insert csv data row by row, when you can use MySQL's LOAD DATA INFILE command. It's 20x faster than inserting row by row.

    Here's a simpler solution:

     true,
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
            )
        );
    } catch (PDOException $e) {
        die("database connection failed: ".$e->getMessage());
    }
    
    $affectedRows = $pdo->exec("
        LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." INTO TABLE `$databasetable`
          FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)."
          LINES TERMINATED BY ".$pdo->quote($lineseparator));
    
    echo "Loaded a total of $affectedRows records from this csv file.\n";
    
    ?>
    

    I tested this with PHP 5.3.26 on a Mac, connecting to MySQL 5.6.14 on Linux.

提交回复
热议问题