Advertisement
michaelyuen

Untitled

Apr 29th, 2018
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.46 KB | None | 0 0
  1. There is a method for updating posts:
  2.  
  3. public function update() {
  4.     // Form data validation rules
  5.     // irrelevant for the question suppressed
  6.  
  7.     $id = $this->input->post('id');
  8.  
  9.     // Upload image
  10.     $config['upload_path'] = './assets/img/posts';
  11.     $config['allowed_types'] = 'jpg|png';
  12.     $config['max_size'] = '2048';
  13.  
  14.     $this->load->library('upload', $config);
  15.  
  16.     $post_image = ''; // set default value to empty
  17.     if (!empty($_FILES['userfile'])) {
  18.         $data = array('upload_data' => $this->upload->data());
  19.         $this->upload->do_upload();
  20.         $post_image = $_FILES['userfile']['name'];
  21.     }
  22.     if ($this->form_validation->run()) {
  23.         // so this will pass empty to update_post if no upload
  24.         $this->Posts_model->update_post($id, $post_image);
  25.         redirect('posts/post/' . $id);
  26.     } else {
  27.         $this->edit($id);
  28.     }
  29. }
  30.  
  31. // change your
  32.  
  33. public function update_post($id, $post_image) {
  34.     $data = [
  35.         'title' => $this->input->post('title'),
  36.         'description' => $this->input->post('desc'),
  37.         'content' => $this->input->post('body'),
  38.         'cat_id' => $this->input->post('category')
  39.     ];
  40.  
  41.     if (!empty($post_image)) {
  42.         // push $post_image to $data only if it's not empty
  43.         $data['post_image'] = $post_image,
  44.     }
  45.  
  46.     $this->db->where('id', $id);
  47.     // so this will only update other keys and not post_image if $data['post_image'] is not set
  48.     return $this->db->update('posts', $data);
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement