我想用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'));
答案 0 :(得分:0)
这个$ dbh对象来自哪里?这不是一个对象。
$sth = $dbh->prepare(
解决方案:
$to_insert_array = array(
'key'=>'value',
...
);
DB::table('table_name')->insert($to_insert_array);