使用Laravel将CSV内容上载到数据库

时间:2018-03-10 00:17:14

标签: php mysql laravel csv file-upload

我正在尝试使用Laravel上传一行CSV文件。它的内容将存储在我已经制作的数据库(MySQL)中,但是我很难这样做。

这是我的表格:

    <center>
    <form action="/csvfileupload" method="post">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <h4><label> Please Select File (CSV only):</label>
    <input type="file" name="csvfile"/></h4>
    <h4><input type="submit" name="upload" value="Upload"/></h4>
    </form>
    {{ csrf_field() }}
    </center>

这是我的路线:

    Route::post('/csvfileupload','Controller@csvfileupload');

这是我的控制器:

function csvfileupload(Request $req)
{
    $title = $req->input('title');
    $address = $req->input('address');
    $Date = $req->input('Date');
    $intro = $req->input('intro');
    $mainbody = $req->input('mainbody');
    $paragraph = $req->input('paragraph');
    $footer = $req->input('footer');

    $data =
    array('title'=>$title,'address'=>$address,'Date'=>$Date,'intro'=>$intro,
   'mainbody'=>$mainbody,'paragraph'=>$paragraph,'footer'=>$footer);
    DB::table('template')->update($data);

    echo "Success";
}

CSV文件:

title,address,Date,intro,mainbody,paragraph,footer
Module Bro,"Hi,",2018-03-14,Attention all students!: This is very 
important!,"Your results are out now on blackboard, you have received a 
grade of:",Comments for your coursework are as follows if you have any 
concerns feel free to contact me at any time.,"Yours Truly, best tutor ever. 
helen d."

我想将它们存储在数据库中,但我该怎么办呢?

1 个答案:

答案 0 :(得分:2)

在HTML表单标记中添加以下代码

<form action="/csvfileupload" method="post" enctype="multipart/form-data">

控制器代码:

public function csvfileupload(Request $req)
{
    if ($request->hasFile('csvfile')) {
        $path = $request->file('csvfile')->getRealPath();
        $data = \Excel::load($path)->get();

        if ($data->count()) {
            foreach ($data as $key => $value) {
                $arr[] = ['title' => $value->title, 
                          'address' => $value->address,
                          'Date' => $value->Date,
                          'intro' => $value->intro,
                          'mainbody' => $value->mainbody,
                          'paragraph' => $value->paragraph,
                          'footer' => $value->footer,

                         ];
            }
            if (!empty($arr)) {
                DB::table('template')->insert($arr);

                return "Success";
            }
        }
    }
}

注意:请确保使用数据库设置(如

)更新.env文件

E.g

    DB_CONNECTION=mysql

    DB_HOST=127.0.0.1

    DB_PORT=3306

    DB_DATABASE=your_database_name

    DB_USERNAME=root

    DB_PASSWORD=