2015-06-05 63 views
0

我想用laravel將csv文件上傳到數據庫中,但它不能正常工作。據得到的消息Laravel上傳Csv錯誤

調用一個成員函數準備()非對象

我的控制器內的。

這裏是我的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' => '[email protected]', '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' => '[email protected]')); 

回答

0

從你來自哪裏該$胸徑對象?這不是一個對象。

$sth = $dbh->prepare( 

解決方案:

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

從聯賽/ CSV包 – utdev

+0

你去掉上面的代碼的東西讓它工作? – utdev