I am using CodeIgniter. I have a form and fields are first_name
, middle_name
, last_name
, profile_pic
. I am able to insert the data in the database.
For example, I added data
first_name:xyz
middle_name:poiu
last_name:wertfg
profile_pic:abcvd.png
Now I am on the edit page, I fetch all the data from the database and displaying on the edit page. I have to update the records. So I added
first_name:12kjh
middle_name:12lkiuy
last_name:96lkjhg
Note:: I haven't added the image.
I am getting the issue on profile_pic
. Profile_pic is also updating and getting the empty in the database.
I have to check if there is already image on profile_pic. If yes then update the same name if no then adds a new image or else send empty if user not adding an image.
What condition I have to use? Controller
if ($this->form_validation->run() == FALSE)
{
//some validation error code
} else {
//Get Last Image Name
$get_image_name = $this->List_model->getImageName($id);
echo $get_image_name //getting image name
$config=[
'upload_path' =>'./uploads/images',
'allowed_types' =>'gif|jpg|png|jpeg',
'file_name' =>uniqid().time().date("dmy")
];
$this->load->library('upload', $config);
if ($this->upload->do_upload('profile_pic'))
{
$profile_pic_set = $this->upload->data('file_name');
}
else{
$profile_pic_set = "";
}
$updateData= array(
'first_name' => trim($this->input->post('first_name')),
'middle_name' => trim($this->input->post('middle_name')),
'last_name' => trim($this->input->post('last_name')),
'profile_pic' => $profile_pic_set,
);
$secure_updateData = $this->security->xss_clean($updateData);
if($secure_updateData)
{
$this->db->where('member_id', $id);
$this->db->update('members', $secure_updateData);
$response['error'] = true;
$response['msg'] = "Member Successfully Saved";
echo json_encode($response);
}else{
alert("Sometning wrong! please check the internet connection and try again");
}
}
First you need to check the updated data,ensure there is a file or not
$updateData= array(
'first_name' => trim($this->input->post('first_name')),
'middle_name' => trim($this->input->post('middle_name')),
'last_name' => trim($this->input->post('last_name')),
'profile_pic' => '',
);
if(!file_exists($_FILES['profile_pic']['tmp_name'])) {
unset($updateData['profile_pic']);
}else{
$config=[
'upload_path' =>'./uploads/images',
'allowed_types' =>'gif|jpg|png|jpeg',
'file_name' =>uniqid().time().date("dmy")
];
$this->load->library('upload', $config);
if ($this->upload->do_upload('profile_pic')){
$updateData['profile_pic_set'] = $this->upload->data('file_name');
}else{
$updateData['profile_pic_set'] = "";
}
}
//UPDATE YOUR DATA HERE
$secure_updateData = $this->security->xss_clean($updateData);
if($secure_updateData){
$this->db->where('member_id', $id);
$this->db->update('members', $secure_updateData);
$response['error'] = true;
$response['msg'] = "Member Successfully Saved";
echo json_encode($response);
}