简体   繁体   English

将csv数据导入到mysql中的所有内容都归于一列

[英]Imported csv data into mysql all ends up in one column

I want to import CSV file data to MySQL. 我想将CSV文件数据导入MySQL。
This is the code: 这是代码:

if (is_uploaded_file($_FILES['excelfile']['tmp_name'])) {
    echo "<h1>" . "File ". $_FILES['excelfile']['name'] ." Upload Done!" . "</h1>";
    echo "<h2>File Upload:</h2>";
    readfile($_FILES['excelfile']['tmp_name']);
}

$handle = fopen($_FILES['excelfile']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $import="INSERT into city(city_name,days) values('$data[0]','$data[1]')";
    mysql_query($import) or die(mysql_error());
}

fclose($handle);
echo "<br><strong>Import Done.</strong><br>

The result just inserts into one column: 结果仅插入到一列中: 在此处输入图片说明

The fields in your CSV file are separated by semicolon, but you're using comma in your call to fgetcsv() . CSV文件中的字段用分号分隔,但是在对fgetcsv()调用中使用逗号。 Try 尝试

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

You can get the data on CSV file following code. 您可以通过以下代码在CSV文件上获取数据。

if ($_FILES['excelfile']['size'] > 0) {
    $mimes = array('application/vnd.ms-excel', 'text/plain', 'text/csv', 'text/tsv');
    //get the csv file
    $file = $_FILES['excelfile']['tmp_name'];
    $handle = fopen($file, "r");

    $data = array();
    while (!feof($handle)) {
        $data[] = fgetcsv($handle);
    }
}

Now you have data of CSV on $data array.So using foreach and then you can insert data into database. 现在您已经在$data数组上$data了CSV $data因此可以使用foreach然后将数据插入数据库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM