无法将数据从csv插入到具有未知列数的mysql数据库

时间:2016-03-02 13:45:10

标签: php mysql csv

我已经有几天这个非常讨厌的问题了,我做了研究和一切,但它似乎比我的编程技巧和知识更大。

我的情况是用户可以在我的数据库中的表中定义自定义列,现在我需要将CSV个文件导入到该用户的自定义表中。因为我最近发现表格需要"动态"这就是我之前处理导入的方式:

$file = $_FILES['file']['tmp_name'];
        $handle = fopen($file, "r");
        $name = $_FILES['file']['name'];
    if (strrpos($name, '.csv', -4)) {//handling the csv file
                    do {
                        if ($data[0]) {
                            $mysqli->query("INSERT INTO `test` (`name`, `surname`, `email`) VALUES
                            (
                                '" . addslashes($data[0]) . "',
                                '" . addslashes($data[1]) . "',
                                '" . addslashes($data[2]) . "'
                            )
                        ");

                        }
                    } while ($data = fgetcsv($handle, 1000, ",", "'"));

这与静态表完美配合。但由于我不知道有多少列表,我尝试过这样的事情:

构建查询方法

 if (strrpos($name, '.csv', -4)) {//ubacije vrijednosti csv fajla u bazu
                do {
                    if ($data[0]) {
                        $query = "INSERT INTO $tabela (";
                        $last = end($anotherArray);
                        foreach ($anotherArray as $something) {//$anotherArray contains names of fields in user's custom table
                            if ($something != $last) {
                                $query .= "" . $something . ",";
                            } else {
                                $query .= "" . $something . ")";
                            }
                        }

                        $query .= "VALUES (";
                        foreach($data as $val){
                       $query .= "'$val',";
}


    }while ($data = fgetcsv($handle, 1000, ",", "'"));

                $query=rtrim($query,',');
                $query.=")";
                //var_dump($query);
                $rez=$mysqli->query($query);
                //var_dump($rez);

但是这段代码的问题是,如果csv文件包含例如2个或更多列,如下所示:enter image description here

一切都成为VALUES部分查询的一部分。因此查询如下所示:"INSERT INTO tabela12312334 (user_facebook_id,ime,prezime) VALUES('123123123','Ognjen','Babic','123123123','Neven',Babic)"当然,字段数与值的数量相同。

请帮我解决这个问题,我绝望了。

1 个答案:

答案 0 :(得分:0)

尝试一下

LOAD DATA LOCAL INFILE  
'c:/path-to-csv-file/your-file.csv'
INTO TABLE your_awesome_table  
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(field_1,field_2 , field_3);

NB: 作为字段标题的第一行,您可能必须在CSV文件中包含标题