简体   繁体   中英

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?

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],
        ),

尝试在sprintf函数之前清理查询字符串。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM