无法将CSV文件导入到SQL(使用PDO)

时间:2019-06-18 09:23:24

标签: php pdo export-to-csv

我有一个名为'result.csv'的.csv文件。它包含:

1,2,3,4,6,5,7

我想使用此代码将.csv文件导入SQL中的my_table(我想将.csv值放入'id_2'列),但是此代码无法正常工作。

<?php
    $host = "localhost";
    $db_name = "tsp";
    $username = "root";
    $password = "";
    $conn = new PDO("mysql:host=" .$host . ";dbname=" . $db_name, $username, $password);

define('CSV_PATH','C:/Users/user/Downloads/'); // CSV file path

$csv_file = CSV_PATH . "result.csv"; // Name of CSV file
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
$i = 0;
while (!feof($csvfile))
{
   $csv_data[] = fgets($csvfile, 1024);
   $csv_array = explode(",", $csv_data[$i]);
   $insert_csv = array();
   $insert_csv['id_2'] = $csv_array[0];

   $sql = $conn->prepare("INSERT INTO my_table(id_2) VALUES('','".$insert_csv['id_2'].")");
   $sql->execute();

   $i++;
}

fclose($csvfile);
?>

我该怎么办?谢谢您的帮助

1 个答案:

答案 0 :(得分:0)

这是一个很晚的答案,但我希望我能帮上忙。请考虑以下内容:

  • 使用file()读取文件内容

  • 您的INSERT语句不正确-列列表中只有一列,但是有两个值("INSERT INTO my_table(id_2) VALUES('','".$insert_csv['id_2'].")")。

  • 使用prepared statement执行INSERT语句。

CSV文件(result.csv):

1,2,3,4,6,5,7
11,12,13,14,16,15,17

PHP:

<?php
// Connection
$host     = "localhost";
$db_name  = "tsp";
$username = "root";
$password = "";
try {
    $conn = new PDO("mysql:host=" .$host . ";dbname=" . $db_name, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Error connecting to SQL Server".$e->getMessage());
}

// Read file
define('CSV_PATH', 'C:/Users/user/Downloads/');
$filename = CSV_PATH."result.csv";
$file     = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

// Read lines and insert data
try {
    $sql = $conn->prepare("INSERT INTO my_table(id_2) VALUES(?)");
    foreach ($file as $row) {
        $ids = explode(',', $row);
        foreach($ids as $id) {
            $sql->bindValue(1, $id);
            $sql->execute();
            echo $id."<br>";
        }
    }
} catch(PDOException $e) {
    die("Error executing query" );
}

?>