从csv到PHP MySQL的LOAD DATA LOCAL INFILE循环

时间:2014-07-22 18:38:17

标签: php mysql csv

我试图整理一个工作脚本,将一些1200行CSV文件加载到MySQL表中。 CSV文件将在我有LOAD DATA LOCAL INFILE指向的目录中按顺序命名。它可以很好地加载第一个文件(有三个),但最后两个文件最终得到了空表(尽管表格确实已经创建)。我试图在将来最终将其用于n个数据文件,但是现在想要弄清楚只是用循环导入三个。任何想法为什么第一个文件将导入,但其他两个返回空表?

$con=mysqli_connect("address","username","password","database");
    if(!$con){
        echo "Connection could not be established: " . mysqli_connect_error($con);
    }
    //Create Table for Sensor "n" data
    for ($i=1; $i<4; $i++){
    $table="CREATE TABLE sensor$i(Column1 VARCHAR(30), Column2 VARCHAR(30), Column3 INT, Column4 INT, Column5 INT, Column6 INT, Column7 INT)";
    if(mysqli_query($con,$table)){
        echo "Table sensor$i created successfully!";
    }
    else{
        echo "Error creating table: " . mysqli_error($con);
    }

    $file = "/Directory/sensor$i.csv"; //Load data file from local directory
    echo $file;//my debug check to output whether or not the $file was picking up unique files per loop
    $sql= "LOAD DATA LOCAL INFILE '$file' INTO TABLE sensor$i FIELDS TERMINATED BY ',' (Column1, Column2, Column3, Column4, Column5, Column6, Column7)";//Set LOAD DATA command into variable for query
    mysqli_query($con,$sql) or die(mysql_error());//Query MySQL DB to load data
}

非常感谢!

0 个答案:

没有答案