Saving multiple images for one product using one t

2019-09-07 04:01发布

问题:

I am new in code igniter. Here is what I am trying to do. I have lists of products stored in database table name products. For each products i need to insert multiple images. I have created two tables, products and productimage. I have made the product_id of table productimage the foreign key, referencing the product_id of table products. Now i want to save the datas from form. Here is what i did previously Saving images in a single row by imploding But it became quite difficult for me to manage CRUD(like editing and deleting pictures). So i am trying to do the above mentioned way. I am not finding the way to start. Can anyone please instruct me, how can I start?

Okay now I have done some coding here. This is my controller:

    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');

   class Products extends CI_Controller{

   public function __construct()
   {
  parent::__construct();
   $this->load->model('product_model');
   $this->load->helper(array('form','url'));
   //Codeigniter : Write Less Do More
   }

   public function index()
  {
   $data['products']=$this->product_model->get_product();
   $this->load->view('/landing_page',$data);
   }

   public function create()
   {
    #code
    $this->load->helper('form');
    $this->load->library('form_validation');
    $this->form_validation->set_rules('product_name','Product_Name','required');

   if($this->form_validation->run()=== FALSE)
   {
    $this->load->view('products/create');
   }
  else {
    $this->product_model->set_product();
    $data['products']=$this->product_model->get_product();
    redirect('/');
   }
 }
 }

This is my model:

          <?php
    defined('BASEPATH') OR exit('No direct script access allowed');

    class Product_model extends CI_Model{

   public function __construct()
  {
   $this->load->database();
   parent::__construct();
   //Codeigniter : Write Less Do More
   }

    public function get_product()
   {
  #code
  $query=$this->db->get('products');
  return $query->result_array();
    }

    public function set_product($id=0)
   {
   #code
   // if($this->input->post('userSubmit')){
      $picture=array();
      $count=count($_FILES['picture']['name']);
      //Check whether user upload picture
      if(!empty($_FILES['picture']['name'])){

          foreach($_FILES as $value)
          {
            for($s=0; $s<=$count-1; $s++)
            {
              $_FILES['picture']['name']=$value['name'][$s];
    $_FILES['picture']['type']    = $value['type'][$s];
    $_FILES['picture']['tmp_name'] = $value['tmp_name'][$s];
    $_FILES['picture']['error']       = $value['error'][$s];
    $_FILES['picture']['size']    = $value['size'][$s];

    $config['upload_path'] = 'uploads/images/';
    $config['allowed_types'] = 'jpg|jpeg|png|gif';
    $config['file_name'] = $_FILES['picture']['name'];

    //Load upload library and initialize configuration
    $this->load->library('upload',$config);
    $this->upload->initialize($config);
          // print_r($value['name'][$s]);exit;
          if($this->upload->do_upload('picture')){
              $uploadData = $this->upload->data();
              $picture[] = $uploadData['file_name'];
          }
          else{
              $picture = '';
          }
        }
      }
      }//end of first if

      else{
          $picture = '';
      }

  $data=array(
    'product_name'=>$this->input->post('product_name')
  );
  $picture=array(
    'product_id'=>$this->db->get('products',$id),
    'picture_image'=>$picture
  );
  if ($id==0)
  {
    return $this->db->insert('products',$data);
    return $this->db->insert('images',$picture);
  }
  else {
    $this->db->where('id',$id);
    return $this->db->update('products',$data);
    return $this->db->update('images',$picture);
   }
   }
   }

Noe the case is when my form opens i am being able to fill product name and upload image files. When i submit it doesn't throws any errors too. But only product name is stored in products table and nothing happens to images table. No any images are inserted. Neither any error is thrown by browser. Simply images table is empty. What's the problem here?

回答1:

Let me help you with the Controller .. You need to check for all the uploaded files. They are $_FILES. Loop through the array, upload them on the server and than call a model function to add them in your product Images table

If CI Upload is too tricky for you. Use the following Controller function

public function upload_images()
{
// following IF statement only checks if the user is logged in or not
if($this->session->userdata['id'] && $this->session->userdata['type']=='user')
{
    if($_FILES)
    {
        // check whether there are files uploaded / posted
        if(isset($_FILES['files'])){
            $data['errors']= array();
            $extensions = array("jpeg","jpg","png");

            //Loop through the uploaded files

            foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){

                $file_name = $key.$_FILES['files']['name'][$key];
                $file_size =$_FILES['files']['size'][$key];
                $file_tmp =$_FILES['files']['tmp_name'][$key];
                $i=1;
                if($file_size > 2097152){
                    $data['errors'][$i]='File '.$i.' size must be less than 2 MB';
                    $i++;
                }
                // Set upload destination directory
                $desired_dir="uploads";
                if(empty($data['errors'])==true){
                    if(is_dir($desired_dir)==false){
                        mkdir("$desired_dir", 0700);        // Create directory if it does not exist
                    }
                    if(is_dir("$desired_dir/".$file_name)==false){
                        // Upload the file. 
                        move_uploaded_file($file_tmp,"uploads/".$file_name);
                        // Call a function from model to save the name of the image in images table along with entity id
                        $this->post_model->addImage('property_images',$file_name,$this->uri->segment(3));
                    }else{                                  //rename the file if another one exist
                        $new_dir="uploads/".$file_name.time();
                        rename($file_tmp,$new_dir) ;
                    }
                }else{
                    $data['contact']=$this->admin_model->getContactDetails();
                    $data['images']=$this->post_model->getPropertyImages($this->uri->segment(3));
                    //load views
                }
            }
            if(empty($data['errors']))
            {
                redirect(base_url().'dashboard');
            }
            else
            {
                $data['contact']=$this->admin_model->getContactDetails();
                $data['images']=$this->post_model->getPropertyImages($this->uri->segment(3));
                //load views
            }
        }
    }
    else
    {
        //Load view
    }
}
else
{
    redirect(base_url().'user/login');
}

}


回答2:

Incase anyone is having the same problem then here is the solution. Just do this in your upload function.(code by my friend Amani Ben azzouz)

    public function set_product($id=0){
   $picture=array();
   $count=count($_FILES['picture']['name']);
   //Check whether user upload picture
   if(!empty($_FILES['picture']['name'])){
       foreach($_FILES as $value){
           for($s=0; $s<=$count-1; $s++){
               $_FILES['picture']['name']=$value['name'][$s];
               $_FILES['picture']['type']    = $value['type'][$s];
               $_FILES['picture']['tmp_name'] = $value['tmp_name'][$s];
               $_FILES['picture']['error']       = $value['error'][$s];
               $_FILES['picture']['size']    = $value['size'][$s];
               $config['upload_path'] = 'uploads/images/';
               $config['allowed_types'] = 'jpg|jpeg|png|gif';
               $config['file_name'] = $_FILES['picture']['name'];

               //Load upload library and initialize configuration
               $this->load->library('upload',$config);
               $this->upload->initialize($config);
               // print_r($value['name'][$s]);exit;
               if($this->upload->do_upload('picture')){
                   $uploadData = $this->upload->data();
                   $picture[] = $uploadData['file_name'];
               }
           }
       }
   }//end of first if
   $data=array('product_name'=>$this->input->post('product_name'));

   if ($id==0){
        $this->db->insert('products',$data);
        $last_id = $this->db->insert_id();
        if(!empty($picture)){
            foreach($picture as $p_index=>$p_value) {
               $this->db->insert('images', array('product_id'=>$last_id,'images'=>$p_value));
            }
        }
   }
   else {
       $this->db->where('id',$id);
       $this->db->update('products',$data);
       if(!empty($picture)){
           foreach($picture as $p_index=>$p_value) {
              $this->db->update('images', array('product_id'=>$last_id,'images'=>$p_value) ); // --> this one?
           }
       }
    }
  }

This is for inserting and updating too. If you simply want do insert just delete the parameter passed as 'id' and cut that if and else part write a plain code of inside 'if'.



回答3:

function contract_upload(){ // function to call from your view. 
    $data = array();
    // If file upload form submitted
    if(!empty($_FILES['files']['name']) AND !empty('user_id')){
        $filesCount = count($_FILES['files']['name']);
        for($i = 0; $i < $filesCount; $i++){
            $_FILES['file']['name']     = $_FILES['files']['name'][$i];
            $_FILES['file']['type']     = $_FILES['files']['type'][$i];
            $_FILES['file']['tmp_name'] = $_FILES['files']['tmp_name'][$i];
            $_FILES['file']['error']    = $_FILES['files']['error'][$i];
            $_FILES['file']['size']     = $_FILES['files']['size'][$i];
            // File upload configuration
            $uploadPath = './uploads/contract/';
            $config['upload_path'] = $uploadPath;
            $config['allowed_types'] = 'jpg|jpeg|png|gif';
            $config['encrypt_name'] = TRUE;
            // Load and initialize upload library
            $this->load->library('upload', $config);
            $this->upload->initialize($config);
            // Upload file to server
            if($this->upload->do_upload('file')){
                // Uploaded file data
                $fileData = $this->upload->data();
                $uploadData[$i]['file_name'] = $fileData['file_name'];
                $uploadData[$i]['emp_id'] = $this->input->post('user_id');
            }
        }
        if(!empty($uploadData)){
            // Insert files data into the database
            $insert = $this->Contract_model->insert($uploadData);
            // Upload status message
            $statusMsg = $insert?'Files uploaded successfully.':'Some problem occurred, please try again.';
            $this->session->set_flashdata('messageactive', $statusMsg);
        }
    }
    redirect('contract'); // redirect link, where do you want to redirect after successful uploading of the file.
}
// Model Function
public function insert($data = array()){
    $insert = $this->db->insert_batch('employee_contract_files', $data); // table name and the data you want to insert into database.
    return $insert?true:false;
}

Remember one thing, you should write your HTML as below:

<input type="file" name="files[]"  multiple />