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?
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.
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.
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.
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.
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],
),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With