CSV File To DB In Yii

CSV File Upload

Using the below code i created the form "importcsvform.php".


<div class="form">
$form=$this->beginWidget('CActiveForm', array(
    'htmlOptions'=>array('enctype' => 'multipart/form-data'),

//echo $form->errorSummary($model); 

<div class="row">
<?php echo $form->labelEx($model,'csvfile'); ?>
    $this->widget('CMultiFileUpload', array(
        'name' => 'csvfile',
        'accept' => 'csv',
        'duplicate' => 'Duplicate file!', 
        'denied' => 'Invalid file type',              
<?php echo $form->error($model,'csvfile'); ?>

<div class="row buttons">
    <?php echo CHtml::submitButton('Import',array("id"=>"Import",'name'=>'Import')); ?>
<?php $this->endWidget(); ?>
</div><!-- form -->

Read CSV In Controller

CSV file contains the data in follwoing format

Name Age
Yii 20
Framework 25

public function actionImport(){
    $model=new Csv;
        // To validate 

            foreach($filelist as $file)
                    $transaction = Yii::app()->db->beginTransaction();
                    $handle = fopen("$file->tempName", "r");
                    $row = 1;
                    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                            $newmodel=new Csv;       
                }catch(Exception $error){

  • What is $_POST[‘csv’]? I can’t find form element has name ‘csv’ in view

    • m bala

      $_POST[‘csv’] is a form name. If we submit the form, we will process the value inside the form

      • I see form’s id is ‘csv-form’. So, why form name is ‘csv’?

        • m bala

          SORRY, It is not a form name. My model name is ‘csv’ and yii will display the input fields like below.

          When we submit the form, we will get it as multidimensional array (csv[name], etc) in controller. so we have to validate the form is submitted or not using $_POST[‘csv’] value,