简体   繁体   中英

Yii2 LOAD DATA LOCAL INFILE

I know there are other solutions to this problem, but it did not work for me.

I am trying to execute a LOAD DATA LOCAL INFILE statement in a MySQL database via a Yii2 website. I have got this working in the past, so I am not sure why it doesn't work anymore.

I get the following error:

SQLSTATE[42000]: Syntax error or access violation: 1148 The used command is not allowed with this MySQL version

I do have the following setting in my db.php config file.

'attributes' => [ PDO::MYSQL_ATTR_LOCAL_INFILE => true ],

I also tried disabling secure-file-priv to no avail.

EDIT

I tried running the following query from Workbench and it throws an error via Workbench as well. However, it works on MySQL 5.7. I am currently using 8.0

LOAD DATA LOCAL INFILE 'D:/Temp/6_attlog.dat' IGNORE
INTO TABLE att_log
FIELDS TERMINATED BY '\t' ENCLOSED BY '''' LINES TERMINATED BY '\r\n' IGNORE 0 LINES 
(@id, `date_time`, `dev_id`, `mode`, `work_code`, `work_code1`) SET `id` = TRIM(@id)

EDIT 2

I got it to work with "LOAD DATA INFILE"...

...but it does not work with "LOAD DATA LOCAL INFILE"

Here's the code I was using...

$inFile = str_replace('\\', '/', realpath('uploads/'.$model->file->name));
Yii::$app->db->createCommand('
    LOAD DATA LOCAL 
    INFILE \''.$inFile.'\' IGNORE 
    INTO TABLE att_log 
    FIELDS TERMINATED BY \'\\t\'  
    ENCLOSED BY \'\'\'\' 
    LINES TERMINATED BY \'\r\n\' 
    IGNORE 0 LINES 
    (@id, `date_time`, `dev_id`, `mode`, `work_code`, `work_code1`) 
    SET `id` = TRIM(@id)
')->execute();
unlink($inFile);

Just a suggestion

in PHP you can use single and double quote so you could build you command in a simple an more clear way eg:

  $inFile = str_replace('\\', '/', realpath('uploads/'.$model->file->name));
  Yii::$app->db->createCommand("
      LOAD DATA LOCAL 
      INFILE '".$inFile."' IGNORE 
      INTO TABLE att_log 
      FIELDS TERMINATED BY '\t'  
      ENCLOSED BY '\' 
      LINES TERMINATED BY '\r\n\' 
      IGNORE 0 LINES 
      (@id, `date_time`, `dev_id`, `mode`, `work_code`, `work_code1`) 
      SET `id` = TRIM(@id)
  ")->execute();
  unlink($inFile);

According to MySQL documentation, server needs to be configured to allow LOCAL keyword:

LOCAL works only if your server and your client both have been configured to permit it. For example, if mysqld was started with the local_infile system variable disabled, LOCAL does not work.

https://dev.mysql.com/doc/refman/8.0/en/load-data.html

Are you sure that your server is correctly configured to allow this keyword?

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