【问题标题】:Laravel upload Csv errorLaravel上传Csv错误
【发布时间】:2015-08-20 03:42:28
【问题描述】:

我想使用 laravel 将 csv 文件上传到数据库中,但它无法正常工作。它得到消息

在非对象上调用成员函数prepare()

在我的控制器中。

这是我的 CsvController

public function uploadCsv()
{
    //We are going to insert some data into the users table
    $sth = $dbh->prepare(
        "INSERT INTO products (name, data_required_general, data_default_attribute, data_default_images) 
         VALUES (:name, :data_required_general, :data_default_attribute, data_default_images)"
    );

    $csv = Reader::createFromPath('/csvFile/test.csv');
    $csv->setOffset(1); //because we don't want to insert the header
    $nbInsert = $csv->each(function ($row) use (&$sth) {
        //Do not forget to validate your data before inserting it in your database
        $sth->bindValue(':name', $row[0], PDO::PARAM_STR);
        $sth->bindValue(':data_required_general', $row[1], PDO::PARAM_STR);
        $sth->bindValue(':data_default_attribute', $row[2], PDO::PARAM_STR);
        $sth->bindValue(':data_default_images', $row[3], PDO::PARAM_STR);

        return $sth->execute(); //if the function return false then the iteration will stop
    });
}

我的看法

    <div class="btn-group" role="group"> <!-- ~ btn btn-default btn-file ~ -->
    Upload CSV
    {{ Form::open(array('action' => 'CsvController@uploadCsv', 'method' => 'POST', 'class' => 'btn btn-default')) }}
        {{ Form::file('file','',array('class' => 'form-control', 'accept' => '.csv')) }}
        {{ Form::submit('Upload!', array('class' => 'btn btn-default')) }}
    {{ Form::close() }}
</div>

还有我的路线

Route::post('csvUpload', array('as' => 'uploadCsv', 'uses' => 'CsvController@uploadCsv'));

【问题讨论】:

    标签: csv laravel upload


    【解决方案1】:

    这个 $dbh 对象是从哪里来的?这不是一个对象。

       $sth = $dbh->prepare( 
    

    解决方案:

    $to_insert_array = array(
        'key'=>'value',
        ...
    );
    DB::table('table_name')->insert($to_insert_array);
    

    【讨论】:

    • 来自联赛/csv 包
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 2017-07-29
    • 2017-08-13
    • 1970-01-01
    相关资源
    最近更新 更多