I
I
ITwoolf2019-03-19 13:39:45
Yii
ITwoolf, 2019-03-19 13:39:45

How to import csv files into table/database?

Good afternoon. I will try to describe my problem as succinctly as possible. I have a table of books with the fields ID, Name, Description, Author, Creation_Date and Date_Of_Change. I made the columns in the view using DynaGrid and therefore I already have the opportunity to export goods in csv format. Export files are stored in the download.
- I added another "Import" button in the view - I
registered the code for import in the controller, which I connected with the Import button.
Code in controller:

public function actionImporter()
    {
        //путь к файлу
        $pathToFile = Yii::getAlias('@way7');
        //файл можно загрузить с помощью формы

        if (!file_exists($pathToFile) || !is_readable($pathToFile)) {
            //... код, если файл отсутствует
        }
        $data = array();

        if (($handle = fopen($pathToFile, 'r')) !== false) {
            $i = 0;

            while (($row = fgetcsv($handle, 1000, $delimiter)) !== false) {
                $model = new Kniga1();
                $model->name = $row [0];
                $model->creation_date = $row [1];
                $model->id_avtor1 = $row [2];

                if ($model->validate()) {
                    $model->save();
                } else {
                    //... код в случае ошибки сохранения
                }
            }
            fclose($handle);
        };
        //... код после импорта
    }

I assumed that for import it needs to specify the path from where to get the files. When exporting, the table export in csv format is loaded into downloads. So I thought the import should come from that folder. To do this, I went to the params-local.php folder (as they wrote on the Internet) and created a new alias: And I registered this alias (@way7) in the controller when I wrote the import code. But when I click on the "Import" button, the browser gives me an error fopen(/Downloads/grid-export): failed to open stream: No such file or directory Please tell me what I'm doing wrong and how to do it? Perhaps the solution to this problem is simple, but I'm a beginner and therefore difficult.
Yii::setAlias('@way7', '/Загрузки/grid-export');

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2019-03-19
@ITwoolf

Writes that the directory is not found. Your folder path is not complete. You specify /loads....
Start searching from the root. I'm not sure that your downloads are in the root. Most likely they are in the web folder. Your path must be complete from the root to this folder. Or use Alial web. @web/downloads/....

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question