我正在为一家销售公司开发一个网站。我想添加大量员工数据,这将是一个 CSV 文件。我需要帮助。一个代码示例将不胜感激,因为我是这方面的新手。此代码应先上传 CSV,然后将其导入 MySQL。提前致谢!
user2980063
问问题
4545 次
1 回答
1
有一个带有文件上传表单的视图,然后有一个带有控制器调用的上传函数的 csv_model。这个函数应该包含看起来有点像这样的代码:
if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0 && $_FILES['userfile']['error'] == 0) {
// Upload the file:
if (!is_dir($this->upload_path)) mkdir($this->upload_path,0777,TRUE);
$config['upload_path'] = $this->upload_path;
$config['allowed_types'] = 'csv';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
echo 'Error: '; print_r($error); die();
return $error;
}
else
{
// It's uploaded, so open it, loop through it and do what you need to do
$data = array('upload_data' => $this->upload->data());
$file_path = $data['upload_data']['full_path'];
$row = 1;
$db_row = array();
if (($handle = fopen($file_path, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$db_row[$row]['xxx'] = $data[0];
// Any database insertion goes here...
}
}
}}
于 2013-11-11T18:51:39.550 回答