Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload CSV file to MySQL using Laravel

I'm trying to upload a csv file to the table users in Laravel.

This is my php script:

private function _import_csv($path, $filename)
    {

        $csv = $path . $filename;
        $query = sprintf("LOAD DATA local INFILE '%s' INTO TABLE users FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '\"' LINES TERMINATED BY '\\n' IGNORE 0 LINES (`firstname`, `lastname`, `username`, `gender`, `email`, `country`, `ethnicity`, `education`  )", addslashes($csv));
    return DB::connection()->getpdo()->exec($query);

}



public function uploadUsers(){


    if (Input::hasFile('fileInput')){

        $file = Input::file('fileInput');
        $name = time() . '-' . $file->getClientOriginalName();

        $path = 'public/uploads/'.date('Y/m/');

        $file->move($path, $name);
        $this->_import_csv($path, $name);

    }

    return Response::json(["success"=>true]);
}

But I'm getting this error:

{"error":{"type":"ErrorException","message":"PDO::exec(): LOAD DATA LOCAL INFILE forbidden","file":"C:\\wamp\\www\\lc2\\laravel\\app\\controllers\\UsersController.php","line":224}}

I don't know whats wrong. Can anybody please help me?

like image 965
user1012181 Avatar asked Feb 28 '15 04:02

user1012181


People also ask

How to import CSV data to MySQL database with Laravel?

Import CSV Data to MySQL Database with Laravel Last updated on February 2, 2019 by Yogesh Singh In CSV file you can store data in comma-separated string format. Sometimes require to import existing CSV file data to MySQL database. For this, you can either directly read the file or upload and then read the file for insert data.

How do I run a Laravel project from a CSV file?

Then, run the laravel project by running the command php artisan serve. Open laravel project in browser with URL like 127.0.0.1:8000 or laravel-csv.test. Click the Import Data button, then select the CSV file and click submit.

How to import CSV into mysql table using load data local?

Open table to which the data is loaded. Review the data, click Apply button. MySQL workbench will display a dialog “Apply SQL Script to Database”, click Apply button to insert data into the table. We have shown you how to import CSV into MySQL table using LOAD DATA LOCAL and using MySQL Workbench.

How do I upload a file in Laravel?

Create a file uploading controller; we define the business logic for uploading and storing files in Laravel. Execute the command to create the controller. Open app/Http/Controllers/FileUpload.php file, and we need to define the two methods to handle the file upload.


1 Answers

Please try it

Set PDO Connection options

Set attribute PDO::MYSQL_ATTR_LOCAL_INFILE in database.php

'mysql' => array(
            ....
            'options'    => [PDO::MYSQL_ATTR_LOCAL_INFILE=>true],
        ),
like image 123
Jay Dhameliya Avatar answered Oct 19 '22 23:10

Jay Dhameliya