Home>

I want to put specific records from a csv file into an array and register them in the DB all at once.
$this->Materials->patchEntities ($bulk_material, $data);
However, I get an error.

Is the argument passed to patchEntities wrong?
If i have any improvement measures, please cooperate.

public function bulkadd ()
    {
      $bulk_material = $this->Materials->newEmptyEntity ();
      if ($this->request->is ('post')) {
        $tmp_file_name = $_FILES ["csv"] ["tmp_name"];
        // Array to store the read record registration data
        $data = array ();
        if (is_uploaded_file ($tmp_file_name)) {
            $csv_contents = fopen ($tmp_file_name, "r");
            $line = 1;
            // Array to put the column name (assuming CSV with the column name in the first line)
            // [0] =>'itemcode', [1] =>'name', etc.
            $keys = array ();
            while (($csv_content = fgetcsv ($csv_contents, 0, ","))! == FALSE) {
              if ($line == 1) {
              // The first line is the process of getting the column name
                // [0] =>'itemcode', [1] =>'name'
                $keys = mb_convert_encoding ($csv_content,'UTF-8','ASCII, JIS, UTF-8, SJIS');// Encoding
                $line ++;
              } elseif ($line<= 2) {
                // After the first line, skip the second line because it is a character for Excel input
                $line ++;
                continue;continue;
              } else {
                // Make an associative array with the column name obtained in the first line as the key
                for ($i = 0;$i<count ($keys);$i ++) {
                        // The number of rows starts at 1 and the array number starts at 0, so adjust with -1.
                        // $i is the number of data starting from 0 on each line
                        $data [$line-3] [$keys [$i]] = mb_convert_encoding ($csv_content [$i],'UTF-8','ASCII, JIS, UTF-8, SJIS');// Encode
                        // $data [] = mb_convert_encoding ($csv_content,'UTF-8','ASCII, JIS, UTF-8, SJIS');// Encode
                }
                $line ++;
              }
            }
        }
        // I get an error here
        $bulk_material = $this->Materials->patchEntities ($bulk_material, $data);

     if ($this->Materials->saveMany () ($bulk_material)) {
        $this->Flash->success (__ ('Added CSV file'));
        return $this->redirect (['action' =>'index']);
      }
        $this->Flash->error (__ ('Could not add CSV file'));
     }
     $this->set (compact ('bulk_material'));
    }