Codeigniter when i update the form others are updating but image path disappears
Form Submit
user name update
password update
image url delete
Form Submit
user name update
password update
Not -> image url delete
CONTROLLER
public function profil_guncelle($id)
{
if(!empty($_FILES['avatar']['name'])){
$config['upload_path'] = 'uploads';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['width'] = 150;
$config['height'] = 50;
$config['file_name'] = $_FILES['avatar']['name'];
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('avatar')){
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
}else{
$picture = '';
}
}else{
$picture = '';
}
$this->form_validation->set_rules('user_pass', 'Parola', 'trim|required');
$this->form_validation->set_rules('user_mail', 'E-Posta', 'trim|required');
if ($this->form_validation->run() == FALSE) {
$this->session->set_userdata('profil_guncelle', validation_errors());
$upload_error = array('error' => $this->upload->display_errors());
redirect(base_url().'admin/users/profil/'.$id);
}else{
$data=array(
'user_pass' => $this->input->post('user_pass'),
'user_mail' => $this->input->post('user_mail'),
'avatar' => $picture
);
if ($this->Database_Model->profil_guncelle($data, $id) ==true) {
$this->session->set_flashdata('profil_guncelle', 'Bilgileriniz başarıyla güncellendi.');
redirect(base_url().'admin/users/profil/'.$id);
}
}
}
}
DATABASE MODEL
public function profil_guncelle($data, $id){
$this->db->set($data);
$this->db->where('id', $id);
if ($this->db->update('users') ===true) {
return true;
}else{
return false;
}
}
First you are set $picture become '' if $_FILES['avatar']['name'] is empty.
than when you are trying update data
$data=array(
'user_pass' => $this->input->post('user_pass'),
'user_mail' => $this->input->post('user_mail'),
'avatar' => $picture
);
of course $picture will be set to '' if the images files are empty. you change the array become :
$data=array(
'user_pass' => $this->input->post('user_pass'),
'user_mail' => $this->input->post('user_mail'),
);
if($picture != ''){
$data['avatar'] = $picture;
}
Related
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;
}
}
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.
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;
}
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()
I have a small issue on this code for the to add a product on my system I am using V_add_pro function, when the image upload part is coming I am facing some issues to validate, so that I used a different function to validate through callback, its not working. the main issue is i am saving the image name only to the database, so how to return the image name only?
public function v_add_pro(){
$this->load->model('B_menu');
$data = array('status' => false, 'msg' => array());
$this->load->library('form_validation');
$this->form_validation->set_rules("pro_name", "name needed", "trim|required");
$this->form_validation->set_rules("pro_price", "price needed", "trim|required");
$this->form_validation->set_rules("pro_desc", "description is needed", "trim|required");
$this->form_validation->set_rules("dropzone", "select an image", "trim|required|callback_validate_image");
$this->form_validation->set_rules("pro_cat", "please select a category","callback_check_default|trim|required");
$this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');
if ($this->form_validation->run()) {
$data['status'] = true;
$pro_data = array(
'pname' => $this->input->post('pro_name'),
'pprice' => $this->input->post('pro_price'),
'pdesc' => $this->input->post('pro_desc'),
'pimage' =>$this->input->post('dropzone'),
'catid' => $this->input->post('pro_cat'),
);
$this->B_menu->add($pro_data);
} else {
foreach ($_POST as $key => $value) {
$data['msg'][$key] = form_error($key);
}
}
echo json_encode($data);
}
//to check the selected value for category
function check_default($post_string)
{
return $post_string == '0' ? FALSE : TRUE;
}
//to upload the image to the correct path
public function validate_image() {
$config = array(
'allowed_types'=>'jpg|png|gif',
'upload_path'=> realpath(APPPATH . '../skin/images'),
'max_size'=>1
);
$this->load->library('upload', $config);
if (!$this->upload->do_upload('dropzone'))
{
$this->form_validation->set_message('validate_image',$this->upload->display_errors());
} else {
$file_info = $this->upload->data();
$img = $file_info['file_name'];
return $img;
}
}
public function validate_image()
{
/* Start: Image Uploading */
$baseurl = $this->config->base_url();
$profile_photo = "";
$profile_path = '';
$config['upload_path'] = './assets/profile_pictures';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
if (!empty($_FILES))
{
$this->file_ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$this->file_name = time() . "." . $this->file_ext;
$config['file_name'] = $this->file_name;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('image', FALSE))
{
echo $this->upload->display_errors();
$this->form_validation->set_message('checkdoc', $data['error'] = $this->upload->display_errors());
if ($_FILES['image']['error'] != 4)
{
return false;
}
}
else
{
$profile_photo = $this->file_name;
$profile_path = $baseurl . "assets/profile_pictures";
return $profile_photo;
}
}
/* End: Image Uploading */
To add-ons I am just saving file name as current timestamp thats it. Also return $imagename and also try to echo this
echo $this->upload->display_errors();
upload library
function upload($upload_path = '', $file_name = ''){
$config = $this->config($upload_path);
$this->CI->load->library('upload' ,$config);
//thuc hien upload
if($this->CI->upload->do_upload($file_name)){
$data = $this->CI->upload->data();
}
else{
//khong upload thanh cong
$data = $this->CI->upload->display_error();
}
return $data;
}
function config($upload_path = ''){
//Khai bao bien cau hinh
$config = array();
//thuc mục chứa file
$config['upload_path'] = $upload_path;
//Định dạng file được phép tải
$config['allowed_types'] = 'jpg|png|gif';
//Dung lượng tối đa
$config['max_size'] = '500';
//Chiều rộng tối đa
$config['max_width'] = '1500';
//Chiều cao tối đa
$config['max_height'] = '1500';
//load thư viện upload
$this->CI->load->library('upload', $config);
return $config;
}
edit action
function edit(){
$id = $this->uri->rsegment('3');
$news = $this->news_model->get_info($id);
if(!$news){
$this->session->set_flashdata('message', 'Không tồn tại bài viết này');
redirect(admin_url('news'));
}
$this->data['news'] = $news;
$this->load->library('form_validation'); //load thư viện
$this->load->helper('form'); //load helper
/*===============================================validate và update data===========================================*/
if( $this->input->post() ){
$this->form_validation->set_rules('title' ,'Tiêu đề bài viết ','required');
$this->form_validation->set_rules('content' ,'Nội dung bài viết','required');
if( $this->form_validation-> run()){
$this->load->library('upload_library');
$upload_path = './upload/news';
$upload_data = $this->upload_library->upload($upload_path, 'image');
$image_link = $this->news_model->get_info($id, 'image_link') ;
if( isset($upload_data['file_name']) ){
$image_link = $upload_data['file_name'];
}
$data = array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'image_link' => $image_link,
'meta_desc' => $this->input->post('meta_desc'),
'meta_key' => $this->input->post('meta_key'),
'created' => now()
);
if($this->news_model->update($news->id , $data)){
$this->session->set_flashdata('message', 'Cập nhật dữ liệu thành công');
}
else{
$this->session->set_flashdata('message', 'Không cập nhật dữ liệu thành công');
}
//chuyển tới trang danh sách quản trị viên
redirect(admin_url('news'));
}
}
$this->data['temp'] = 'admin/news/edit';
$this->load->view('admin/main' , $this->data);
}
I edited the data are not required to upload photos
when I clicked update button without upload file error occurred
$data = $this->CI->upload->display_error();
this is wrong method call. It should be like this
$data = $this->CI->upload->display_errors();
I am inserting some data into the database in my Codeigniter controller
function addsoothingmemory() {
$config['upload_path'] = './uploads2/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '500000';
$config['max_width'] = '100024';
$config['max_height'] = '100768';
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('soothing', $error);
} else {
$imagedata = $this->upload->data();
$data = array(
'image_path' => $imagedata['file_name'],
'title' => $this->input->post('title'),
'user_id' => $this->session->userdata("user_id"),
'feelingrate' => $this->session->userdata("feelingrate"),
'description' => $this->input->post('description')
);
$query = $this->favourite_db->getsoothingcount() + 1;
$this->favourite_db->add_soothingmemory($data);
$count = array('soothingcount' => $query);
$this->favourite_db->updateusercount($count);
$this->load->view('positivepast', $data);
}
}
Model
function add_soothingmemory($data) {
$this->load->database();
$this->db->insert('soothingmemory', $data);
$this->set_session();
return $data;
}
The problem is when the value is inserted into the database it inserts three times creating multiple/duplicate rows.
I had the same problem,
anyhow, in your model,
$this->db->limit(1);
$this->db->insert('soothingmemory', $data);
that way duplicates will be avoided.
Hope it helps
Make the following changes:
function addsoothingmemory() {
$config['upload_path'] = './uploads2/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '500000';
$config['max_width'] = '100024';
$config['max_height'] = '100768';
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('soothing', $error);
} else {
$imagedata = $this->upload->data();
$data = array(
'image_path' => $imagedata['file_name'],
'title' => $this->input->post('title'),
'user_id' => $this->session->userdata("user_id"),
'feelingrate' => $this->session->userdata("feelingrate"),
'description' => $this->input->post('description')
);
$query = $this->favourite_db->getsoothingcount() + 1;
$save = $this->favourite_db->add_soothingmemory($data);
// Move this code into the model
// $count = array('soothingcount' => $query);
if($save == true){
$this->favourite_db->updateusercount($query);
$this->load->view('positivepast', $data);
}else{
//do something else
}
}
}
In the model
function add_soothingmemory($data) {
$this->load->database();
$save = $this->db->insert('soothingmemory', $data);
//This condition will check, if the $data was save
if($save == true){
//If is save, it will set the session and return true
$this->set_session();
return true;
}else{
return false;
}
}
I'm curious to know in $this->upload->do_upload('img') field name is passing mandotory not.I have seen several example in stackoverflow where do_upload() not taking any argument as file field name.But in case of mine without field name file not uploaded.I want to know which is correct syntax?
2)How do i bypass the file upload validation when there is no file being uploaded.If there is no file(image) in the form then $this->upload->display_errors() will not be called.my code is below
function add()
{
if ($this->input->server('REQUEST_METHOD') === 'POST')
{
$this->form_validation->set_rules('category', 'Category Name', 'required');
if ($this->form_validation->run())
{
$data_to_store = array(
'category' => $this->input->post('category'),
'description' => $this->input->post('description'),
'parent'=>'0'
);
$last_id=$this->admin_category_model->add_category($data_to_store);
$config['upload_path'] ='./uploads/';
$config['allowed_types'] = 'gif|jpg|png|GIF|JPG|PNG';
$config['remove_spaces'] = TRUE;
$config['max_size'] = '0';
$config['file_name'] =$last_id.'_'.$_FILES['img']['name'];
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
if($this->upload->do_upload('img'))
{
$data = array('upload_data' => $this->upload->data());
$config2['image_library'] = 'gd2';
$config2['source_image'] = $data['upload_data']['full_path'];
$config2['new_image'] ='./uploads/thumb/'.$data['upload_data']['file_name'];
$config2['create_thumb'] = FALSE;
$config2['maintain_ratio'] = TRUE;
$config2['width'] = 35;
$config2['height'] = 35;
$this->load->library('image_lib',$config2);
$this->image_lib->resize();
$data_to_store = array(
'img' => $config['file_name'],
);
$this->admin_category_model->update_category($last_id,$data_to_store);
$this->session->set_flashdata('flash_message', 'Record Added');
redirect('admin_category/index');
}
else
{
$data['error']=$this->upload->display_errors();
}
}
}
$data['title']='Add Category';
$data['main_content'] = 'admin/add_category';
$this->load->view('admin/includes/template', $data);
}
1st) No, not necessary, by default it will take the name userfile.
2nd) Say for example your fieldname is img check like this:
if( $_FILES['img']['name'] != "" ){
//your upload code here
}