将大型CSV文件导入Mysql数据库

时间:2020-09-16 19:32:15

标签: php mysql laravel csv csv-import

我有用于将大型csv文件导入mysql数据库的Core php代码,并且工作正常。我想在laravel中使用相同的技术,并将其转换为laravel的控制器功能。下面我附上了我的核心php代码,如果有人可以,请帮助我。

<?php
session_start();
require_once('Database.php');
if(isset($_SESSION['admin']) and $_SESSION['admin']!="")
{

if (!empty($_FILES['csvfile']['name']))
{
//$mimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
$mimes = array(
    'text/csv',
    'text/plain',
    'application/csv',
    'text/comma-separated-values',
    'application/excel',
    'application/vnd.ms-excel',
    'application/vnd.msexcel',
    'text/anytext',
    'application/octet-stream',
    'application/txt',
);
if(in_array($_FILES['csvfile']['type'],$mimes)){
    $file=$_FILES['csvfile']['tmp_name'];
    $fname=basename($file);
 
    //$sql="delete from calls";
    //mysql_query($sql) or die(mysql_error());
    $sql="LOAD DATA LOCAL INFILE '/tmp/$fname' 
        INTO TABLE calls
        FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'
        LINES TERMINATED BY '\n' 
        (`account_code`,`source`,`destination`,`dbcontext`,`caller_id`,`channel`,`destination-channel`,`lastapp`,`lastdata`,`start`,`answer`,`end`,`duration`,`billseconds`,`disposition`,`amaflag`,`call_id`,`userfield`)";
        mysql_query($sql) or die(mysql_error());

    header('location:import-csv.php?success=1');
    unlink($file);
} else {
    header('Location:import-csv.php?invalid=1');
}

}
else header('Location:import-csv.php?mandatory=1');
}
else header('Location:index.php');


?>

在这里,我尝试将其转换为功能,但功能不完整。 我实际上不知道如何在该函数中执行/运行此查询。该功能在Controller中。

public function import(Request $request) 
    {
        
        //Excel::import(new CallsImport,request()->file('file'));
        //return redirect()->route('calls.importExportView')->withFlashSuccess(__('Added.'));
        if ($request->hasFile('file')){
            $csv = $request->file('file');
            
            $query="LOAD DATA INFILE '$csv' 
                  INTO TABLE calls
                  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'
                  LINES TERMINATED BY '\n' 
                  (`account_code`,`source`,`destination`,`dbcontext`,`caller_id`,`channel`,`destination-channel`,`lastapp`,`lastdata`,`start`,`answer`,`end`,`duration`,`billseconds`,`disposition`,`amaflag`,`call_id`,`userfield`)";


                    }

    }

0 个答案:

没有答案