我怎样才能按列逐列上传csv文件。在数据库中

时间:2019-12-16 12:00:20

标签: php mysql csv

想使用php作为列明智地上传一个csv文件。我尝试上传它,但未正确上传数据。this is my csv file

it is my database

include_once'dbConfig.php';

if(isset($ _ POST ['importSubmit'])){

// Allowed mime types
$csvMimes = array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain');

// Validate whether selected file is a CSV file
if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'], $csvMimes)){

    // If the file is uploaded
    if(is_uploaded_file($_FILES['file']['tmp_name'])){

        // Open uploaded CSV file with read-only mode
        $csvFile = fopen($_FILES['file']['tmp_name'], 'r');

        //Skip the first line
        //fgetcsv($csvFile);

        // Parse data from CSV file line by line
        while(($line = fgetcsv($csvFile)) !== FALSE){
            // $col_count=count($line);

            // Get row data
            $name   = $line[0];
            $email  = $line[1];

            // Check whether member already exists in the database with the same email
            $prevQuery = "SELECT id FROM csv WHERE email = '".$line[1]."'";
            $prevResult = $db->query($prevQuery);

            if($prevResult->num_rows > 0){
                // Update member data in the database
                $db->query("UPDATE csv SET name = '".$name."', email = '".$email."', modified = NOW() WHERE email = '".$email."'");
            }else{
                //Insert member data in the database
                $db->query("INSERT INTO csv (name, email) VALUES ('".$name."', '".$email."') ");
            }
        }

        // Close opened CSV file
        fclose($csvFile);

        $qstring = '?status=succ';
    }else{
        $qstring = '?status=err';
    }
}else{
    $qstring = '?status=invalid_file';
}

}

//重定向到列表页面 header(“ Location:index.php”。$ qstring);

0 个答案:

没有答案