使用Yii框架将csv导入mysql

时间:2013-06-17 13:48:02

标签: php mysql yii

我将csv文件上传到数据库时遇到问题。这是我的观点:

<?php
$this->breadcrumbs = array(
__('People') => array('/contacts'),
__('Persons') => array('admin'),
__('Manage'),
);?>



<h1><?php echo __('People'); ?> <small><?php echo __('import contacts'); ?></small></h1><br/>
<div class="form">

<?php
$form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'service-form',
'enableAjaxValidation'=>false,
'method'=>'post',
'type'=>'horizontal',
'htmlOptions'=>array(
    'enctype'=>'multipart/form-data'
)
)); ?>

<fieldset>


    <?php echo $form->errorSummary($model, 'Opps!!!', null, array('class'=>'alert alert-error span12')); ?>

    <div class="control-group">     
        <div class="span4">
                            <div class="control-group <?php if ($model->hasErrors('postcode')) echo "error"; ?>">
    <?php echo $form->labelEx($model,'file'); ?>
    <?php echo $form->fileField($model,'file'); ?>
    <?php echo $form->error($model,'file'); ?>
                        </div>


        </div>
    </div>

    <div class="form-actions">
        <?php $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'submit', 'type'=>'primary', 'icon'=>'ok white', 'label'=>'UPLOAD')); ?>
        <?php $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'reset', 'icon'=>'remove', 'label'=>'Reset')); ?>
    </div>

</fieldset>

<?php $this->endWidget(); ?>

</div><!-- form -->

这是我的模特:

<?php
class UserImportForm extends CFormModel
{
public $file;
/**
 * @return array validation rules for model attributes.
 */
public function rules()
{
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(  
         array('file', 'file', 
                                        'types'=>'csv',
                                        'maxSize'=>1024 * 1024 * 10, // 10MB
                                        'tooLarge'=>'The file was larger than 10MB. Please upload a smaller file.',
                                        'allowEmpty' => false
                          ),
               );
}

/**
 * @return array customized attribute labels (name=>label)
 */
public function attributeLabels()
{
    return array(
        'file' => 'Select file',
    );
 }

}
?>

这是我在Controller中的功能

public function actionImportCSV()
    {
       $model=new UserImportForm;

       if(isset($_POST['UserImportForm']))
         {

           $model->attributes=$_POST['UserImportForm'];

           if($model->validate())
             {

              $csvFile=CUploadedFile::getInstance($model,'file');  
              $tempLoc=$csvFile->getTempName();

                $sql="LOAD DATA LOCAL INFILE '".$tempLoc."'
    INTO TABLE `contacts`
    ";
                $connection=Yii::app()->db;
                $transaction=$connection->beginTransaction();
                    try
                        {

                            $connection->createCommand($sql)->execute();
                            $transaction->commit();
                        }
                        catch(Exception $e) // an exception is raised if a query fails
                         {
                            echo "<pre>";
                            print_r($e);
                            echo "</pre>";
                            exit;
                            $transaction->rollBack();

                         }
                  $this->redirect(Yii::app()->createUrl("/contacts/importCSV"));


             }
         }  

       $this->render("importcsv",array('model'=>$model));
     }

我的LOAD DATA有问题,导致mySQL版本不支持LOAD DATA。任何人都知道如何替换加载数据以导入csv文件?

2 个答案:

答案 0 :(得分:1)

如果您使用的是MySQL版本,则不支持LOAD DATA,那么您确实使用的是旧版本。当前的在线文档包括每个提到的版本中的LOAD DATA,尽管LOCAL子句仅支持3.22.6。

也许真正的问题是,如果你没有指定FIELDS子句,它会将文件视为

FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\'
LINES TERMINATED by '\n' STARTING  BY ''

已指定。这是Unix(Linux)文本格式的TAB分隔值文件。要使其逗号分隔,请指定:

LOAD DATA LOCAL INFILE 'data.txt' INTO TABLE tbl_name
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"';

如果您希望从Windows计算机上获取文件,则可能需要包含

LINES TERMINATED BY '\r\n'

在FIELDS条款之后。

答案 1 :(得分:1)

按照以下说明操作:

https://github.com/Ardem/yii-importcsv-extension

我按照readme.md文件中描述的简单步骤执行了3个简单的步骤,它工作得很轻松。