csv文件上传后自动生成MySQL表

时间:2017-07-31 14:17:10

标签: php mysql csv

我正在开发一个PHP / MySQL项目,它必须验证以下任务:

- > 用户一次上传多个大型CSV文件,在MySQL表格中使用相同的列名称(X,Y,Z)

- > 网络应用必须在每个csv文件列之间执行算术运算

- > 用户可以在操作后将csv文件下载为Excel文件

对于上传部分,我需要找到一种方法在数据库中为每个上传的csv文件自动生成一个表 - 而不是提前创建它 - 因为用户应该能够上传他想要的任意数量的文件

我试图设置一个包含一个创建表的while循环,循环从0到$ var,这是用户希望上传的csv文件的数量,但它不会添加任何表,这里是该部分的代码:

    $con= getdb();

$var=$_GET["quantity"];

mysql_query("set $i=0;
             while $i<`".$var."` do
             create table `couche".$var."` ( X float NOT NULL,Y float NOT NULL,Z float NOT NULL);
             set $i= $i+1;
             end while");
 }

1 个答案:

答案 0 :(得分:0)

您好,您可以使用以下方式实现它:

<?php 

//database connection details
$link = mysqli_connect('localhost','root','password','db_name') or die('Could not connect to MySQL');

// path where your CSV file is located
define('CSV_PATH','/var/www/html/skerp_scripts/');

// Name of your CSV file
$csv_file = CSV_PATH . "importItems.csv";

if (($handle = fopen($csv_file, "r")) !== FALSE) {        
    $header = true;  //If there is a header in first row then set it to true
    while (($data = fgetcsv($handle, 100000, ",")) !== FALSE) {
    if($header == true){
        /* Here you can perform checks whether all the column are as expected 
           for Eg: in CSV1 : id, firstname, lastname, age
            in CSV2 : firstname, age ,id

            Than you can tell the user that there is a misatch
         */
        $header = false;
        continue;
    }
    $column1 = $data[0];
    $column2 = $data[1];
    $column3 = $data[2];

    $calculation = $column1 * $column3;
    $result = mysqli_query($link, "INSERT INTO table_name (column1, column2, column3)" VALUES($column1, $column2, $calculation));

    }
}
echo "File data successfully imported to database!!"; 
mysqli_close($connect);