0

I am new to codeigniter and I am having problem in edit item image, not that it don't get update as it do but there are too many images in the upload folder directory.

What I want to do is I want the previously stored image to be deleted in the upload directory when I update new image.

Here is my controller:

function edit($shop_id = null){

        if ( ! $this->ion_auth->logged_in() OR ! $this->ion_auth->is_admin())
        {
            redirect('auth', 'refresh');
        }
        /* Breadcrumbs */
        $this->data['breadcrumb'] = $this->breadcrumbs->show();

        /* Variables */
        $tables = $this->config->item('tables', 'ion_auth');

        $this->data['shop_id']   = $shop_id;
        /* Get all category */          
        $this->data['shopInfo'] = $this->shop_model->getShopInfo($shop_id);
        //echo "<pre>";print_r( $this->data['shopInfo']);echo "</pre>";exit;

        /* Validate form input */
        $this->form_validation->set_rules('shop_name', 'Shop Name', 'trim|required'); 
        $this->form_validation->set_rules('shop_latidude', 'Shop Latidude', 'trim|required'); 
        $this->form_validation->set_rules('shop_longitude', 'Shop Longitude', 'trim|required');   



        if($this->form_validation->run() == true) {
            $config['upload_path'] =  './assets/uploads/shop/';
            //die(var_dump(is_dir($config['upload_path'])));
            $config['allowed_types'] = 'gif|jpg|png';
            $config['max_size']    = '1024';
            $config['overwrite'] = TRUE;

            $this->load->library('upload', $config);
            $this->upload->initialize($config);
            $img = "logo";

            $img_upload = $this->upload->do_upload($img);
            $data  = $this->upload->data();
            $file  = array('file_name' => $data['file_name'] );           
            $data  = array('upload_data' => $this->upload->data());
            $photo = base_url().'assets/uploads/shop/'.$file['file_name'];

            if($img_upload == 1 ) $post_photo = $photo;
            else $post_photo = $this->input->post('hidden_photo');

            if($this->input->post('status')){
                $status = 1;
            }else{
                $status = 0;
            }
            $shopInfo = array(
                    'shop_name'     =>  $this->input->post('shop_name'),
                    'merchant_id'   =>  $this->input->post('merchant_id'),
                    'photo'         =>  $post_photo,
                    'description'   =>  $this->input->post('shop_desc'),
                    'registered_date'=> date('Y-m-d H:i:s'),
                    'is_active'     =>  1,
                    'shop_location' =>  $this->input->post('shop_loc'),
                    'shop_address'  =>  $this->input->post('shop_add'),
                    'shop_phone'    =>  $this->input->post('shop_ph'),
                    'shop_latitude' =>  $this->input->post('shop_latidude'),
                    'shop_longitude'=>  $this->input->post('shop_longitude'),
                    'open_hour' => $this->input->post('open_hour'),
                    'close_hour' => $this->input->post('close_hour'),
                    'remark' => $this->input->post('remark'),
                    'approved' => $status
                );

            $this->shop_model->shopUpdate($shop_id, $shopInfo);

            redirect(base_url() . 'admin/shop', 'refresh');

        } else {

            $this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
            /* Load Template */
            $this->data['merchant'] = $this->merchant_model->getAllMerchants();
            $this->template->admin_render("admin/shop/edit", $this->data);
        }

    }

Here is my Model:

function shopUpdate($shop_id, $shopInfo) {
        $this->db->where('shop_id', $shop_id);
        if($shopInfo) {
            $query = $this->db->update('shop', $shopInfo);
            if ($query) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
Si Thu
  • 19
  • 1
  • 8
  • You are getting old image in shopInfo, you can delete old image before update new one, please see this answer will help you https://stackoverflow.com/questions/9747897/deleting-a-file-using-php-codeigniter – Nil Jan 03 '19 at 09:03
  • Is your new image uploading with this code? – Danish Ali Jan 03 '19 at 09:19
  • Danish Ali, Yes my image is uploading with this code, it isn't just deleting previous one in upload directory. – Si Thu Jan 03 '19 at 09:55

3 Answers3

0
 function shopUpdate($shop_id, $shopInfo) {
     $q = $this->db->select('photo')->where('shop_id', $shop_id)->get('shop');
       if ($q->num_rows() > 0) {
        $imgName = $q->row();
// image path must be './admin/shop'
            unlink("./{image pathe}/".$imgName);
       } 

       $this->db->where('shop_id', $shop_id);
        if($shopInfo) {
            $query = $this->db->update('shop', $shopInfo);
            if ($query) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }    
    }

you got file name when image got uploaded so get the file name where you are going to update and delete file first. Use unlink to delete file. run update query. you just need to change in model for updating and deleting at same time.

Rajeev Ranjan
  • 4,152
  • 3
  • 28
  • 41
Masih Ansari
  • 467
  • 3
  • 9
0

First, check if new image uploading or not

$new_image = $_FILES['userfile']['name'] ? $_FILES['userfile']['name'] : '';
if($new_image != ''){
    $old_image = $this->shop_model->getOlgImage($shop_id);
    if(isset($old_image) && file_exists('image-path/photo.jpg')){
        unlink('image-path/image');
    }
}

Old image is now deleted. Upload new

$config['upload_path'] =  './assets/uploads/shop/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size']    = '1024';
$config['overwrite'] = TRUE;

$this->load->library('upload', $config);
$this->upload->initialize($config);
$img = "logo";

Give name of your input type file name to $this->upload->do_upload() not variable

No need to add $this->upload->data() twice

if($this->upload->do_upload('userfile')){

$data  = $this->upload->data();
$photo = base_url().'assets/uploads/shop/'.$data['file_name'];

$post_photo = $photo;
} else $post_photo = $this->input->post('hidden_photo');

if($this->input->post('status')){
    $status = 1;
}else{
    $status = 0;
}

Get old image

public function getOldImage($shop_id){
    return $this->db->get_where('shop', ['shop_id' => $shop_id])->row()->photo;
}
Danish Ali
  • 2,354
  • 3
  • 15
  • 26
  • Old image is deleted if new image has same file name and extension but i want it deleted regardless of name and extendsion. – Si Thu Jan 03 '19 at 10:25
  • There is no issue if the newly uploaded image has the same name or extension. And the second thing is you are getting photo name from DB so the image will delete independently – Danish Ali Jan 03 '19 at 10:28
  • Bro the thing is the images in the upload directory. All the images of shop that are uploaded are store in upload directory which is assets/uploads/shop. So the images in this directory are not get delete when updated. – Si Thu Jan 03 '19 at 11:01
0

First, you need to get image name from the database by ID then update record. Once the record is updated then you can delete that image the folder directory.

function shopUpdate($shop_id, $shopInfo) {
       //fetch image name from the database by shop_id
       $imageName = $this->db->select('photo')->where('shop_id', $shop_id)->get('shop');

        $this->db->where('shop_id', $shop_id);
        if($shopInfo) {
            $query = $this->db->update('shop', $shopInfo);
            if ($query) {
             //record is updated successfully now delete that image from folder
             if ($imageName->num_rows() > 0) {              
                unlink("./{image pathe}/".$imageName->row());
              } 

                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

unlink()

Gufran Hasan
  • 8,910
  • 7
  • 38
  • 51