I am trying to update firstname,lastname,image in codeigniter,But whenever i update only first_name and last_name(not image) then image column become null in mysql,Where i am wrong Here is my code
Here is my model
$add_data['first_name'] = ($this->input->post('first_name') && !empty($this->input->post('first_name'))) ? $this->input->post('first_name') : NULL;
$add_data['last_name'] = ($this->input->post('last_name') && !empty($this->input->post('last_name'))) ? $this->input->post('last_name') : NULL;
$saveArr = [];
if(!empty($this->input->post('first_name'))){
$saveArr['first_name'] = $this->input->post('first_name');
}
if(!empty($this->input->post('last_name'))){
$saveArr['last_name'] = $this->input->post('last_name');
}
if(!file_exists($_FILES['image']['tmp_name']) || !is_uploaded_file($_FILES['image']['tmp_name']))
{
$saveArr['image'] = $_FILES['image'];
}
else
{
$filename=time().uniqid(rand()).$_FILES['image']['name'];
move_uploaded_file($_FILES["image"]["tmp_name"], "images/" . $filename);
$saveArr['image']=$filename;
}
$this->db->where('id',$add_data['user_id']);
$query=$this->db->update('users', $saveArr);
In both condition you set $saveArr['image']
, you just need to set $saveArr['image']
when upload new image. so just remove line $saveArr['image'] = $_FILES['image'];
Use below updated code.
$add_data['first_name'] = ($this->input->post('first_name') && !empty($this->input->post('first_name'))) ? $this->input->post('first_name') : NULL;
$add_data['last_name'] = ($this->input->post('last_name') && !empty($this->input->post('last_name'))) ? $this->input->post('last_name') : NULL;
$saveArr = [];
if(!empty($this->input->post('first_name'))){
$saveArr['first_name'] = $this->input->post('first_name');
}
if(!empty($this->input->post('last_name'))){
$saveArr['last_name'] = $this->input->post('last_name');
}
if(!file_exists($_FILES['image']['tmp_name']) || !is_uploaded_file($_FILES['image']['tmp_name']))
{
}
else
{
$filename=time().uniqid(rand()).$_FILES['image']['name'];
move_uploaded_file($_FILES["image"]["tmp_name"], "images/" . $filename);
$saveArr['image']=$filename;
}
$this->db->where('id',$add_data['user_id']);
$query=$this->db->update('users', $saveArr);
From what I understand (I don't do PHP or CodeIgniter) your code always specifies the image column so it will always be updated. You need logic that will only update that column if you have a value.