Importing data from xls,csv to Mysql using Yii 2.0 Framework

aneesh s picture aneesh s · Jun 2, 2015 · Viewed 12k times · Source

I need to import data from XLS,CSV file into MySql database using YII 2.0 Framework,

XLS, CSV files contains datas which should to imported to one table in Mysql DB, Please provide any information to proceed.

Answer

Kalai S picture Kalai S · Jun 2, 2015

I hope this will help

public function actionCreate()
    {
        $model = new Import();

        if ($model->load(Yii::$app->request->post()) ) {

            $model->file = UploadedFile::getInstance($model, 'file');

            if ( $model->file )
                {
                    $time = time();
                    $model->file->saveAs('csv/' .$time. '.' . $model->file->extension);
                    $model->file = 'csv/' .$time. '.' . $model->file->extension;

                     $handle = fopen($model->file, "r");
                     while (($fileop = fgetcsv($handle, 1000, ",")) !== false) 
                     {
                        $name = $fileop[0];
                        $age = $fileop[1];
                        $location = $fileop[2];
                        // print_r($fileop);exit();
                        $sql = "INSERT INTO details(name, age, location) VALUES ('$name', '$age', '$location')";
                        $query = Yii::$app->db->createCommand($sql)->execute();
                     }

                     if ($query) 
                     {
                        echo "data upload successfully";
                     }

                }

            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }