我的CSV文件看起来像: 如何每次更新数据库表csv文件在codeigniter中上传?
我需要的是每一个我上传CSV文件时,我需要更新数据库表,我的意思是,如果在csv文件中的中等存在于数据库中我必须更新该行。如果中在csv文件中不存在数据库中我必须将新行插入到数据库表。
当前我成功上传了csv文件和存储在数据库表中的数据。
我的控制器看起来像:
public function importcsv()
{
$data['menu'] = $this->AdminModel->get_menu();
$data['error'] = ''; //initialize image upload error array to empty
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '1000';
$this->load->library('upload', $config);
// If upload failed, display error
if (!$this->upload->do_upload())
{
$data['error'] = $this->upload->display_errors();
$this->load->view('csvindex', $data);
}
else
{
$file_data = $this->upload->data();
$file_path = './assets/uploads/'.$file_data['file_name'];
if ($this->csvimport->get_array($file_path))
{
$csv_array = $this->csvimport->get_array($file_path);
foreach ($csv_array as $row)
{
$mid=$row['mid'];
$insert_data = array(
'mid'=>$mid,
'category'=>$row['category'],
'name'=>$row['name'],
'price'=>$row['price'],
'description'=>$row['description'],
);
$this->AdminModel->insert_csv($insert_data);
}
$this->session->set_flashdata('success', 'Csv Data Imported Succesfully');
redirect(base_url().'Admin/menu');
}
else
$data['error'] = "Error occured";
$this->load->view('csvindex', $data);
}
}
我觉得CSV文件中的数据读取到数组$ insert_data我想以后我需要将其与中期在数据库中比较表。这怎么可能?我是新来的。事先感谢。
我在我的控制器,它的外观进行修改:
public function importcsv()
{
$data['menu'] = $this->AdminModel->get_menu();
$data['error'] = ''; //initialize image upload error array to empty
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '1000';
$this->load->library('upload', $config);
// If upload failed, display error
if (!$this->upload->do_upload())
{
$data['error'] = $this->upload->display_errors();
$this->load->view('csvindex', $data);
}
else
{
$file_data = $this->upload->data();
$file_path = './assets/uploads/'.$file_data['file_name'];
if ($this->csvimport->get_array($file_path))
{
$csv_array = $this->csvimport->get_array($file_path);
foreach ($csv_array as $row)
{
$data1['mid']=$row['mid'];
$data1['category']=$row['category'];
$data1['name']=$row['name'];
$data1['price']=$row['price'];
$data1['description']=$row['description'];
if($this->db->where('mid', $data1['mid']))
{
$this->db->update('menu', $data1);
}
if($this->db->where("mid !=",$data1['mid']))
{
$this->db->insert('menu', $data1);
}
}
$this->session->set_flashdata('success', 'Csv Data Imported Succesfully');
redirect(base_url().'Admin/menu');
}
else
{
$data['error'] = "Error occured";
$this->load->view('csvindex', $data);
}
}
}
现在我可以更新数据通过
if($this->db->where('mid', $data1['mid']))
{
$this->db->update('menu', $data1);
}
其工作正常,但使用条件:
if($this->db->where("mid !=",$data1['mid']))
{
$this->db->insert('menu', $data1);
}
整个csv文件数据重新进入表格菜单。我需要比较中旬在菜单表和中旬 CSV文件,如果中旬在csv文件在菜单表不存在,我需要插入相应的记录到菜单表。
为什么我需要在代码中完成所有更改?
是'mid'唯一吗? – ArtisticPhoenix
是插入记录之前mid是唯一的 –
,您可以检查是否存在相同的mid。如果存在更新,则插入。你可以用一个单一的SQL查询 – Anish