简体   繁体   中英

Imported csv data into mysql all ends up in one column

I want to import CSV file data to 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() . Try

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

You can get the data on CSV file following code.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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